我写了一个 bash 脚本,但由于我是一个自学者 bash 菜鸟,我想问我是否可以更有效地检查给定的参数。我也用谷歌搜索了这个问题并在这里检查了主题,但到目前为止我看到的例子太复杂了。在 python3 中,有很多更简单的方法,但我想在 bash 中它有点复杂。
#!/bin/bash
ERR_MSG="You did not give the argument required"
if [[ ${1?$ERR_MSG} == "a" ]]; then
echo "ABC"
elif [[ ${1?$ERR_MSG} == "b" ]]; then
echo "123"
elif [[ ${1?$ERR_MSG} == "c" ]]; then
echo ".*?"
else
echo "You did not provide the argument correctly"
exit 1
fi
答案1
只接受单个参数的脚本,该参数必须是a
、b
或c
:
#!/bin/bash
if [[ $# -ne 1 ]]; then
echo 'Too many/few arguments, expecting one' >&2
exit 1
fi
case $1 in
a|b|c) # Ok
;;
*)
# The wrong first argument.
echo 'Expected "a", "b", or "c"' >&2
exit 1
esac
# rest of code here
如果您想要进行正确的选项解析并希望接受-a
、-b
、 或-c
作为不带参数的选项以及-d
带参数的选项。
#!/bin/bash
# Default values:
opt_a=false
opt_b=false
opt_c=false
opt_d='no value given'
# It's the : after d that signifies that it takes an option argument.
while getopts abcd: opt; do
case $opt in
a) opt_a=true ;;
b) opt_b=true ;;
c) opt_c=true ;;
d) opt_d=$OPTARG ;;
*) echo 'error in command line parsing' >&2
exit 1
esac
done
shift "$(( OPTIND - 1 ))"
# Command line parsing is done now.
# The code below acts on the used options.
# This code would typically do sanity checks,
# like emitting errors for incompatible options,
# missing options etc.
"$opt_a" && echo 'Got the -a option'
"$opt_b" && echo 'Got the -b option'
"$opt_c" && echo 'Got the -c option'
printf 'Option -d: %s\n' "$opt_d"
if [[ $# -gt 0 ]]; then
echo 'Further operands:'
printf '\t%s\n' "$@"
fi
# The rest of your code goes here.
测试:
$ ./script -d 'hello bumblebee' -ac
Got the -a option
Got the -c option
Option -d: hello bumblebee
$ ./script
Option -d: no value given
$ ./script -q
script: illegal option -- q
error in command line parsing
$ ./script -adboo 1 2 3
Got the -a option
Option -d: boo
Further operands:
1
2
3
选项解析在第一个非选项参数处或在 处终止--
。请注意,由于-d
需要一个参数,因此-a
在以下示例中被视为该参数:
$ ./script -d -a -- -c -b
Option -d: -a
Further operands:
-c
-b
答案2
将此代码复制到文件中。 (不要忘记chmod +x
)这应该可以满足您的需要。
#!/bin/bash
VERSION="0.0.1"
ACCEPTED_SERVER="server"
ACCEPTED_USER="user"
usage()
{
echo " $(basename $0) [-v] [-h] -u user -s server"
exit
}
version()
{
echo "Current version: $VERSION"
}
get_opts()
{
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-u|--user)
shift
USER="$1"
shift
;;
-s|--server)
shift
SERVER="$1"
shift
;;
-h|--help)
usage
exit
;;
-v|--version)
version
exit
;;
esac
done
}
# echo " arguments: $#"
get_opts $*
if [ $# -gt 4 ] || [ $# -lt 1 ]; then
usage
fi
echo "$SERVER -- $ACCEPTED_SERVER"
if ! [ "$SERVER" = "$ACCEPTED_SERVER" ]; then
echo "Wrong server: $SERVER"
echo "Try with user: $ACCEPTED_SERVER"
usage
else
echo "Correct server: $SERVER"
fi
if ! [ "$USER" = "$ACCEPTED_USER" ]; then
echo "Wrong user: $USER"
echo "Try with user: $ACCEPTED_USER"
usage
else
echo "Correct user: $USER"
fi
echo "Correct! - Server: $SERVER - User: $USER"
然后你可以添加功能用途、版本等。
usage()
{
echo "[-v] [-h] [-u user] [-s server] task"
}