【发布时间】:2016-04-15 02:09:28
【问题描述】:
我创建了一个带有 1 个必需参数的 shell 脚本。我希望它只有在存在 1 个参数时才会运行脚本,否则它将退出。
这是我的代码:
#!/bin/bash
branch=stable
# Custom options/arguments
usage() { # usage code }
while getopts ":bs:" opt; do
case $opt in
b)
branch=development
;;
s)
site=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
if [ -z "${s}" ]; then
echo "
$(tput setaf 1)ERROR:
=========================$(tput sgr0)
$(tput setaf 6)No website name provided:
Format: <example.com>$(tput sgr0)
"
exit 1;
fi
# Rest of the code to run when there are no errors - not putting here as it's irrelevant
所以我希望,当我运行sudo ./nginx-install.sh 时,它会看到没有参数并显示错误消息——确实如此。但是当我执行sudo ./nginx-install.sh -s example.com 时,我只是再次收到错误消息,而我真的希望其余代码能够运行。
谁能指出我在代码中哪里出错了?我是 bash 脚本的新手,所以主要回复 Google 搜索以寻求帮助。
谢谢。
【问题讨论】:
标签: linux bash shell scripting getopts