考虑到:
#!/bin/sh
while getopts ":h" o; do
case "$o" in
h )
"Usage:
sh $(basename "$0") -h Displays help message
sh $(basename "$0") arg Outputs ...
where:
-h help option
arg argument."
exit 0
;;
\? )
echo "Invalid option -$OPTARG" 1>&2
exit 1
;;
: )
echo "Invalid option -$OPTARG requires argument" 1>&2
exit 1
;;
esac
done这个调用返回not found为什么?
$ sh getopts.sh -h
getopts.sh: 12: getopts.sh: Usage:
sh getopts.sh -h Displays help message
sh getopts.sh arg Outputs ...
where:
-h help option
arg argument.: not found这样就行了:
$ sh getopts.sh arg对于这个选项,我期望“无效选项”:
$ sh getopts.sh这样就行了:
$ sh getopts.sh -s x
Invalid option -s发布于 2019-06-28 04:03:41
您似乎错过了打印消息,而是将整个字符串作为要运行的命令传递。在字符串之前添加一个echo
case "$o" in
h )
echo "Usage:
sh $(basename "$0") -h Displays help message
sh $(basename "$0") arg Outputs ...
where:
-h help option
arg argument."
exit 0
;;但是,通常更倾向于使用一种样式来添加heredoc,而不是将多行字符串打印为
show_help() {
cat <<'EOF'
Usage:
sh $(basename "$0") -h Displays help message
sh $(basename "$0") arg Outputs ...
where:
-h help option
arg argument.
EOF
}并使用函数show_help作为-h标志。
对于空参数标志,对getopts()的第一次调用退出循环,因此在循环中不能有句柄。在调用getopts()之前对空参数进行泛型检查
if [ "$#" -eq 0 ]; then
printf 'no argument flags provided\n' >&2
exit 1
fi使用前面对参数标志:h的定义,建议-h不使用任何参数。子句:)仅适用于定义-h以接受参数时,即定义为:h:时。只有在不传递参数的情况下运行它,:)下的代码才会被执行。把整个剧本拼凑起来
#!/usr/bin/env bash
if [ "$#" -eq 0 ]; then
printf 'no argument flags provided\n' >&2
exit 1
fi
show_help() {
cat <<'EOF'
Usage:
sh $(basename "$0") -h Displays help message
sh $(basename "$0") arg Outputs ...
where:
-h help option
arg argument.
EOF
}
while getopts ":h:" opt; do
case "$opt" in
h )
show_help
exit 1
;;
\? )
echo "Invalid option -$OPTARG" 1>&2
exit 1
;;
: )
echo "Invalid option -$OPTARG requires argument" 1>&2
exit 1
;;
esac
done现在就运行它
$ bash script.sh
no argument flags provided
$ bash script.sh -h
Invalid option -h requires argument
$ bash script.sh -s
Invalid option -shttps://unix.stackexchange.com/questions/527385
复制相似问题