bash 脚本 case 语句需要检测特定参数
bash script case statement needs to detect specific arguments
我必须编写此脚本,它将在其自己的行中显示输入的每个条目,并用“*****”分隔每一行。我已经了解了大部分内容,但现在我需要它来检测何时输入 "TestError" and/or "now" 作为参数。如果它们是行中的第一个参数,它现在的设置方式将正确地检测到这些词,我只是不确定如何设置它,无论它在行中是哪个参数,它都会检测到这个词。我还需要 *?如果我需要它为每个其他不是 "TestError" 或 "now" 的参数说 "Do not know what to do with ",目前它会为第一个参数而不是其余的参数做。
它会像现在这样工作吗?还是我必须只使用 *?和 * 案例,只需在 *? case 为了找到 "TestError" "now" 和任何其他参数。
# template.sh
function usage
{
echo "usage: [=11=] arguments ..."
if [ $# -eq 1 ]
then echo "ERROR: "
fi
}
# Script starts after this line.
case in
TestError)
usage $*
;;
now)
time=$(date +%X)
echo "It is now $time"
;;
*?)
echo "My Name"
date
echo
usage
printf "%s\n*****\n" "Do not know what to do with " "$@"
;;
*)
usage
;;
esac
您需要遍历参数,为每个参数执行 case
语句。
for arg in "$@"; do
case $arg in
TestError)
usage $*
;;
now)
time=$(date +%X)
echo "It is now $time"
;;
*?)
echo "My Name"
date
echo
usage
printf "%s\n*****\n" "Do not know what to do with " "$@"
;;
*)
usage
;;
esac
done
*
和 *?
将匹配相同的字符串。您是要按字面意思匹配 ?
(*\?
) 吗?
我必须编写此脚本,它将在其自己的行中显示输入的每个条目,并用“*****”分隔每一行。我已经了解了大部分内容,但现在我需要它来检测何时输入 "TestError" and/or "now" 作为参数。如果它们是行中的第一个参数,它现在的设置方式将正确地检测到这些词,我只是不确定如何设置它,无论它在行中是哪个参数,它都会检测到这个词。我还需要 *?如果我需要它为每个其他不是 "TestError" 或 "now" 的参数说 "Do not know what to do with ",目前它会为第一个参数而不是其余的参数做。
它会像现在这样工作吗?还是我必须只使用 *?和 * 案例,只需在 *? case 为了找到 "TestError" "now" 和任何其他参数。
# template.sh
function usage
{
echo "usage: [=11=] arguments ..."
if [ $# -eq 1 ]
then echo "ERROR: "
fi
}
# Script starts after this line.
case in
TestError)
usage $*
;;
now)
time=$(date +%X)
echo "It is now $time"
;;
*?)
echo "My Name"
date
echo
usage
printf "%s\n*****\n" "Do not know what to do with " "$@"
;;
*)
usage
;;
esac
您需要遍历参数,为每个参数执行 case
语句。
for arg in "$@"; do
case $arg in
TestError)
usage $*
;;
now)
time=$(date +%X)
echo "It is now $time"
;;
*?)
echo "My Name"
date
echo
usage
printf "%s\n*****\n" "Do not know what to do with " "$@"
;;
*)
usage
;;
esac
done
*
和 *?
将匹配相同的字符串。您是要按字面意思匹配 ?
(*\?
) 吗?