我正在执行printf '%s\n' "$@",并使用
pfm "-d DIR" "--directory=DIR"我会犯错误,即:
bash: invalid option -- 'd'
bash: invalid option -- ' '
bash: invalid option -- 'D'
bash: invalid option -- 'I'
bash: invalid option -- 'R'
bash: unrecognized option '--directory=DIR'这是相关代码
printfm ()
{
# Process command line options
shortopts="hVw::"
longopts="help,version,warning:"
opts=$(getopt -o "$shortopts" -l "$longopts" \
-n "$(basename $0)" -- "$@")
if [ $? -eq 0 ]; then
eval "set -- ${opts}"
while [ $# -gt 0 ]; do
case "$1" in
-V|version)
printf "V01 Jul 2021 Wk27"
printf ""
;;
-h|-\?|--help)
help=1
printf "Prints two text strings on two lines.\n"
printf "\$@ TEXT Sentences to print en new lines.\n"
shift
local -r f=0
break
;;
# ......................................................
-w|--warning)
case "$2" in
"1") local -r warn="first"; shift 2 ;;
*) local -r warn="all"; shift 2 ;;
esac
local -r f=1
;;
--)
shift; break ;;
esac
done
else
shorthelp=1 # getopt returned (and reported) an error.
fi
red=$(tput setaf 9)
rgl=$(tput sgr0)
local f=1
if (( f == 1 )); then
# print normal multi-line text
[[ ! -z warn ]] && printf '%s\n' "$@"
# print multi-line warnings
if [[ -n warn && "$warn" == "first" ]]; then
printf '%s\n' ${red}"$1"${rgl} # first line red
printf '%s\n' "${@:2}" # remaining, uncoloured
elif [[ -n warn && "$warn" == "all" ]]; then
printf '%s\n' ${red}"$@"${rgl} # all lines red
fi
fi
return 0
}
alias pfm=printfm 发布于 2021-07-22 15:00:43
这里没有涉及printf的问题。
您的printfm函数接受参数并执行自己的选项解析。它采用的选项是-V、-h、-?、-w、--warning和--help (请注意,在case语句中,--version将被识别,但不能对其进行操作,因为在version前面有一个错误,一个缺失的-- )。当您使用两个参数-d DIR和--directory=DIR调用它时,getopt实用程序会抱怨字符串包含未知的选项。
将类似于选项的非选项参数传递给实用程序或函数的常见方法是使用-- (“双破折号”)从非选项参数中分隔实际选项:
printfm -- "-d DIR" "--directory=DIR"这由您的printfm代码正确地处理,将导致选项解析在--处停止,并允许您以非选项参数的形式接收这两个字符串,即使它们以破折号开头。
相关信息:
https://unix.stackexchange.com/questions/659458
复制相似问题