Checking for the correct number of arguments
如何检查参数的正确数目(一个参数)。如果有人试图在不传递正确数量的参数的情况下调用脚本,并检查以确保命令行参数实际存在并且是一个目录。
1 2 3 4 5 | #!/bin/sh if ["$#" -ne 1 ] || ! [ -d"$1" ]; then echo"Usage: $0 DIRECTORY">&2 exit 1 fi |
翻译:如果number of题元冰槽(numerically)等于1或冰的第一参数不是一个目录,使用两个标准错误输出和出口与一个失效状态码。
享受友好的错误报告:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/bin/sh if ["$#" -ne 1 ]; then echo"Usage: $0 DIRECTORY">&2 exit 1 fi if ! [ -e"$1" ]; then echo"$1 not found">&2 exit 1 fi if ! [ -d"$1" ]; then echo"$1 not a directory">&2 exit 1 fi |
猫script.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var1=$1 var2=$2 if ["$#" -eq 2 ] then if [ -d $var1 ] then echo directory ${var1} exist else echo Directory ${var1} Does not exists fi if [ -d $var2 ] then echo directory ${var2} exist else echo Directory ${var2} Does not exists fi else echo"Arguments are not equals to 2" exit 1 fi |
它像零下execute
1 | ./script.sh directory1 directory2 |
输出将样
1 2 | directory1 exit directory2 Does not exists |
你可以检查的总数题元这是通过在命令行的"
1 2 3 4 5 6 7 8 | sh hello.sh hello-world # I am passing hello-world as argument in command line which will b considered as 1 argument if [ $# -eq 1 ] then echo $1 else echo"invalid argument please pass only one argument" fi |
输出将