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

标签 bash shell

我有一个名为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"

输出是:

6
hello
there
my
name
is
pax     diablo

您的作业的基本思想是:

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

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

相关文章:

bash - 如果第 2 列字段有多个值,则格式化输出

arrays - 从 bash 输出中获取值

bash ->/dev/zero 取消之前的追加

Linux特殊shell含义问题

ruby - 试图杀死端口 8000 混淆的进程

linux - 递归检查所有文件的所有权

bash - 如何使用 "shell prompt"创建 CLI 程序?

shell - Grails shell 在 Grails 3.0.2 中不起作用?

linux - ls -la 和 ls -la > ls-1.txt 的区别

linux - 在bash中如何循环遍历以 "abc"开头的目录和目录 "special-dir"