I was learning bash when I stuck comparing strings inside if statement.
Script: shiftDemo.sh
1 #!/bin/bash
2
3 #using shift keyword to shift CLA
4
5 while true
6 do
7 if [ "$1" = "" ] #change this statement wrt below cases
8 then
9 exit
10 fi
11 echo '$1 is now ' "$1"
12 shift
13 done
I used the following methods:
1.if (( "$1" = "" ))
2.if [ "$1" = "" ]
Observations:
1a) $ bash shiftDemo.sh first second third
`shiftDemo.sh: line 7: ((: = : syntax error: operand expected (error token is "= ")`
1b) $ sh shiftDemo.sh first second third
shiftDemo.sh: 7: shiftDemo.sh: first: not found
$1 is now first
shiftDemo.sh: 7: shiftDemo.sh: second: not found
$1 is now second
shiftDemo.sh: 7: shiftDemo.sh: third: not found
$1 is now third
shiftDemo.sh: 7: shiftDemo.sh: : Permission denied
$1 is now
shiftDemo.sh: 12: shift: can't shift that many
2)In this case, if statement runs fine with both the shells & gives correct output.
$ bash shiftDemo.sh first second third
$1 is now first
$1 is now second
$1 is now third
$ sh shiftDemo.sh first second third
$1 is now first
$1 is now second
$1 is now third
Based on the above observations, my doubts are:
What is wrong with case 1. How can I correct it (I want to use C style syntax throughout my script).
Which syntax is preferred so that it will work with both sh & bash shell ?