sh 布尔短路变量赋值

sh boolean short circuit variable assignment

我正在尝试编写一个将标志作为参数的脚本,因此我希望能够处理它们以任何顺序传递。

这是我目前拥有的:

#!/bin/sh    

numargs=$#
echo $numargs

check_param () {
    if [ "" = "" ]; then
        return 1
    else
        return 0
    fi
}

S=0
T=0
for ((i=1 ; i <= numargs ; i++)); do
    S=$S || check_param  "-s"
    T=$T || check_param  "-t"
    shift
done

echo "$S"
echo "$T"

然而,即使函数在设置参数时返回 1,变量/短路赋值似乎也不起作用。

$ ./script.sh aa ddd fff -s rrr
5
0
0
$ ./script.sh aa ddd fff -s rrr -t
6
0
0

我猜你正试图这样做:

#!/bin/sh    

S=0
T=0

numargs=$#
printf "You passed %s arguments\n" "$numargs"

check_param () {
    if [ "" = "" ]; then
        return 1
    else
        return 0
    fi
}

i=1
while [ "$i" -le "$numargs" ]; do
   current_arg=
   shift
   case $current_arg in
      (-s)
         S=1 ;;
      (-t)
         T=1 ;;
      (*)
         set -- "$@" "$current_arg" ;;
   esac
   i=$((i+1))
done

printf "S flag: %s\n" "$S"
printf "T flag: %s\n" "$T"

if [ $# = 0 ]; then
   printf "No arguments left.\n"
else
   printf "Arguments left (%s):\n" "$#"
   printf "   %s\n" "$@"
fi

我调用了这个脚本 bananachmod +x banana 和:

$ ./banana
You passed 0 arguments
S flag: 0
T flag: 0
No arguments left.
$ ./banana one two -s three
You passed 4 arguments
S flag: 1
T flag: 0
Arguments left (3):
   one
   two
   three

这将告诉您是否给出了 -s-t 选项,并将参数留在参数堆栈中!