我有以下函数应该在新行中写入字符串。有一个警告选项,因此当-w
用户设置时,某些行会变成红色。 -w
允许可选的数字参数-wNUM
。如果NUM
未提供,warn
则设置为1
仅第一行颜色为红色。
我在调用命令时遇到问题
printfm -w -- "First line" "second line"
)。
我已经在声明local warn="1"
之前包含了case
。
("-w"|"--warning")
local warn="1"
case "$2" in
此处列出了该函数
printfm ()
{
# Process command line options
shortopts="hVw::"
longopts="help,version,warning::"
opts=$(getopt -o "$shortopts" -l "$longopts" -n "${0##*/}" -- "$@")
if [ $? -ne 0 ]; then
local shorthelp=1 # getopt returned (and reported) an error.
return
fi
local f=0
if [ $? -eq 0 ]; then
eval "set -- ${opts}"
while [ $# -gt 0 ]; do
case "$1" in
("-V"|"--version")
printf "%s\n" "V01 Jul 2021 Wk27"
declare -i f=0
shift
break
;;
("-h"|-\?|"--help")
printf "%s\n" "Print strings."
declare -i f=0
shift
break
;;
# ------------------------------------
("-w"|"--warning")
case "$2" in
(+([[:digit:]]))
local -r warn="$2"
shift 2
;;
(*)
local -r warn="1"
shift 2
;;
esac
declare -i local f=1
;;
# ----------------------------------------
(--)
declare -i local f=1
shift
break
;;
esac
done
fi
red=$(tput setaf 9)
rgl=$(tput sgr0)
# Print normal text or warnings
if [[ -v $f ]] && (( f != 0 )); then
# print normal multi-line text
[[ ! -v $warn ]] && printf '%s\n' "$@"
# print multi-line warnings
rge='^[0-9]+$'
if [[ -v $warn && "$warn" == "1" ]]; then
printf '%s\n' ${red}"$1"${rgl} # first line red
printf '%s\n' "${@:2}" # remaining, uncoloured
elif [[ -v $warn && "$warn" =~ $rge ]]; then
printf '%s\n' ${red}"$@"${rgl} # all lines red
fi
fi
return 0
}