深入探索Shell脚本:用户输入处理与命令行参数解析
1. 脚本参数的使用与测试
在Shell脚本中使用命令行参数时需格外谨慎。若脚本运行时未提供必要参数,可能会引发错误。例如:
$ ./addem 2
./addem: line 8: 2 + : syntax error: operand expected (error token is " ")
The calculated value is
为避免此类问题,应在使用参数前先进行检查。以下是一个示例脚本 test7.sh :
#!/bin/bash
# testing parameters before use
#
if [ -n "$1" ]
then
echo Hello $1, glad to meet you.
else
echo "Sorry, you did not identify yourself. "
fi
运行示例:
$ ./test7.sh Rich
Hello Rich, glad to meet you.
$ ./test7.sh
Sorry, you did not identify yourself.
此脚本使用 -n 测试来检查 $1 命令行参数是否包含数据。
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



