sh boolean短路变量赋值

时间:2015-02-10 11:00:04

标签: bash sh variable-assignment short-circuiting

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

这是我到目前为止所做的:

#!/bin/sh    

numargs=$#
echo $numargs

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

S=0
T=0
for ((i=1 ; i <= numargs ; i++)); do
    S=$S || check_param $1 "-s"
    T=$T || check_param $1 "-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

1 个答案:

答案 0 :(得分:1)

我猜你正试图这样做:

#!/bin/sh    

S=0
T=0

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

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

i=1
while [ "$i" -le "$numargs" ]; do
   current_arg=$1
   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选项,并将参数保留在参数堆栈上!