linux - 接受可选参数的 Shell 脚本

标签 linux shell sh

如何在 shell 脚本中获取可选参数。

Command Line argument would be: ./abc.sh parm1 parm2 parm3 parm4

这里 parm3 和 parm4 是可选的,具体取决于 parm1(config)

How to write a shell script which will take mandatorily parm1 and parm2 as argument and treat the other two as optional parameters

最佳答案

对所需参数使用 ${var?} 语法:

#!/bin/sh

: ${1:?first argument is required}
: ${2:?second argument is required}

您可以使用 $# 检查参数数量,这样您就可以执行以下操作:

#!/bin/sh
die() { echo "$@" >&2; exit 1; }
case ${1?} in
foo) test $# = 4 || die When first argument is foo, you must give 4 args;;
bar) test $# = 2 || die When first argument is bar, only give 2 args;;
*) ;;
esac

关于linux - 接受可选参数的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323925/

相关文章:

java - 在Linux字体问题上使用PDFBox 2.0.14将PDF转换为Tiff

linux - Gcc 为 c6x 编译 hello.c

MySQLSHOW 抑制 Bash 脚本中的警告

mysql - 使用shell脚本更改mysql root用户密码

bash - 在 shell 脚本中,如何将 stdout 重定向到控制台并将 stdout 和 stderr 重定向到文件?

shell - 5 : Syntax error: “(” unexpected (expecting “then” ) in my script

linux - 为 Raspberry Pi 交叉编译 Linux 内核 - ${CCPREFIX}gcc -v 不起作用

linux - 动态加载和弱符号解析

linux - 通过排除其父文件夹为多个目录创建单个 tar 文件

bash - 合并 CSV 文件 : Appending instead of merging