
在 2 個參數之後,每個參數的開頭不等於 -*
for args in "$@"
do
if [[ ${@: 2} != -* ]]; then
case "$args" in
-q)
if [ ! -z "$2" ]; then
echo "$2"
shift
fi
shift
;;
-w)
if [ ! -z "$2" ]; then
echo "$2"
shift
fi
shift
;;
-e)
if [ ! -z "$2" ]; then
echo "$2"
shift
fi
shift
;;
esac
else
echo "arguments start with '-'"
fi
done
-q s d f g h
僅適用於第一個參數
-q -v -b -n -m -n
和-q -l j u -y d
錯誤的
第一個參數之後,其餘參數不得以字元“-”開頭
if [ ! -z "$2" ];
- 檢查參數是否為空
答案1
您似乎想要驗證除第一個參數外沒有任何參數以破折號開頭。
你可以這樣做:
#!/bin/bash
if [[ $1 != -* ]]; then
printf '1st argument, "%s", does not start with a dash\n' "$1"
exit 1
fi >&2
arg1=$1
shift
for arg do
if [[ $arg == -* ]]; then
printf 'Argument "%s" starts with a dash\n' "$arg"
exit 1
fi
done >&2
echo 'All arguments ok'
printf 'arg 1 = "%s"\n' "$arg1"
printf 'other arg = "%s"\n' "$@"
如果您需要明確第一個參數-q
,請將第一個測試從
[[ $1 != -* ]]
到
[[ $1 != -q ]]