参数测试
在 shell 脚本中使用命令行参数时要当心。如果运行脚本时没有指定所需的参数,则可能会出问题:
- $ ./positional1.sh
- ./positional1.sh: line 5: ((: number <= : syntax error:
- operand expected (error token is "<= ")
- The factorial of is 1
- $
当脚本认为位置变量中应该有数据,而实际上根本没有的时候,脚本很可能会产生错误消息。
这种编写脚本的方法并不可取。在使用位置变量之前一定要检查是否为空:
- $ cat checkpositional1.sh
- #!/bin/bash
- # Using one command-line parameter
- #
- if [ -n "$1" ]
- then
- factorial=1
- for (( number = 1; number <= $1; number++ ))
- do
- factorial=$[ $factorial * $number ]
- done
- echo The factorial of $1 is $factorial
- else
- echo "You did not provide a parameter."
- fi
- exit
- $
- $ ./checkpositional1.sh
- You did not provide a parameter.
- $
- $ ./checkpositional1.sh 3
- The factorial of 3 is 6
- $