gpt4 book ai didi

bash - 如何将命令行参数添加到shell脚本中

转载 作者:行者123 更新时间:2023-11-29 09:41:41 32 4
gpt4 key购买 nike

我有一个名为project2的可执行shell脚本。以下是我的老师给我的关于该项目的指导之一。

This script must accept at least one command line parameter: the directory where its output is to be placed. If that directory is not given on the command line, the script should use a reasonable default directory.

你能告诉我如何让我的脚本接受命令行吗?我以前没有做过类似的事情。任何帮助将不胜感激。非常感谢。

最佳答案

对于bash,命令行参数存储在$1$2等中,而$# > 会给你计数。此外,shift 可用于将它们全部“左”移一位并减少计数。

以下脚本是了解参数如何工作的一个很好的起点:

echo $#
while [[ $# -gt 0 ]] ; do
echo "$1"
shift
done

当你运行它时:

./myprog.sh hello there my name is "pax     diablo"

输出是:

6hellotheremynameispax     diablo

您的作业的基本思想是:

  • 检查参数计数是否为零。
  • 如果为零,请将变量设置为一些有用的默认值。
  • 如果不为零,则根据第一个参数设置该变量。
  • 对该变量执行任何您必须执行的操作。

关于bash - 如何将命令行参数添加到shell脚本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4181999/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com