Search code examples
bashshvariable-assignmentshort-circuiting

sh boolean short circuit variable assignment


I'm trying to write a script that takes flags as parameters, so I want to be able to handle them being passed in any order.

This is what I have so far:

#!/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"

however even though the function is returning 1 when the parameters are set, the variable / short circuit assignment doesn't seem to work.

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

Solution

  • I guess you're trying to do this:

    #!/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
    

    I called this script banana, chmod +x banana and:

    $ ./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
    

    This will tell you whether an -s or -t option is given, and will leave the arguments on the arguments stack!