BASH - Throw usage warning if no command line parameter is passed as an argument
我在这里找到了一个关于计算传递给
现在,我想使用
示例脚本如下,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #!/bin/bash function Usage() { echo"Usage: $0 [-q] [-d]" echo"" echo"where:" echo" -q: Query info" echo" -d: delete info" echo"" } # Exit if no argument is passed in : ${1?Usage} while getopts"qd" opt; do case $opt in q) echo"Query info" ;; d) echo"Delete info" ;; *) Usage; exit 1 ;; esac done |
这个怎么样?
1 2 3 4 5 6 7 8 9 10 11 | function Usage() { echo"Usage: $0 [-q] [-d]" echo"" echo"where:" echo" -q: Query info" echo" -d: delete info" echo"" } # Exit if no argument is passed in : ${1?"$(Usage)"} |
不管怎样,我认为这更具可读性:
1 2 3 | if [ $# -lt 1 ] ; then Usage fi |
另一个办法是这样处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | mode="" while getopts"qdh" opt; do case $opt in q) mode="Query info" ;; d) mode="Delete info" ;; h) Usage exit 0 ;; *) Usage >&2 exit 1 ;; esac done if [ -z"${mode}" ] ; then Usage >&2 exit 1 fi |
您只需要将参数传递到bash脚本。假设bash脚本的名称是
1 2 3 4 | #!/bin/bash # script's name is hello.sh : ${1?"Usage: $0 Argument"} echo hello,$1 |
然后是
然后我们调用脚本,使用以下命令: