1

I have a BASH script to add two numbers where I want to pass two numbers via command line arguments.

cat add.sh a=$1 echo "exit status for a " $? b=$2 echo "exit status for b " $? sum=`expr $a + $b` echo "exit status for sum " $? echo "result is " $sum echo "exit status for result " $? 

When I run the above script without providing any value or arguments, I am getting following output.

$ ./add.sh exit status for a 0 (expecting 1 here) exit status for b 0 (expecting 1 here) expr: syntax error exit status for sum 2 result is exit status for result 0 (expecting 1 here) 

I am expecting value of $? as 1 when I am not providing any arguments via command line, so it must be an error for assigning value of a and b.

Can anyone explain why a=$1 or b=$2 doesn't return exit status 1 when NO value is supplied via command line? Why it returns 0 ?

20
  • 1
    Because parameter expansion on an unset variable is not an error by default. So unless you set -u these are valid, see man set Commented Jan 14, 2018 at 19:15
  • 1
    BTW, did you read the very first comment, by tomix86? It would seem to give you exactly what you're asking for (though I don't advise its use). See also BashFAQ #112. Commented Jan 14, 2018 at 19:19
  • 1
    That's really not what you want to do here. You want to check whether you have passed enough arguments, with (( $# >= 2 )) for example. Commented Jan 14, 2018 at 19:20
  • 1
    Or a=${1?First argument is mandatory}; b=${2?Second argument is mandatory} Commented Jan 14, 2018 at 19:21
  • 3
    Run the script after set -u? No. Put set -u in the script. Commented Jan 14, 2018 at 19:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.