Wednesday, April 23, 2014

Bash conditionals

#!/bin/bash
set -x
MYVAR=3
if [ ${MYVAR} = 1 ]; then
    : First option
elif [ ${MYVAR} = 2 ]; then
    : Second option
elif [ ${MYVAR} = 3 ]; then
    : Third option
fi

->

+ MYVAR=3
+ '[' 3 = 1 ']'
+ '[' 3 = 2 ']'
+ '[' 3 = 3 ']'
+ : Third option

You need to watch out for whitespace, as bash is sensitive to whitespace

#!/bin/bash
set -x
MYVAR=3
if [${MYVAR} = 1 ]; then
    : First option
elif [ ${MYVAR} = 2 ]; then
    : Second option
elif [ ${MYVAR} = 3 ]; then
    : Third option
fi

->

+ MYVAR=3
+ '[3' = 1 ']'
./test.sh: line 4: [3: command not found
+ '[' 3 = 2 ']'
+ '[' 3 = 3 ']'
+ : Third option


Very, very sensitive to whitespace

#!/bin/bash
set -x
MYVAR=3
if [ ${MYVAR}=1 ]; then
    : First option
elif [ ${MYVAR} = 2 ]; then
    : Second option
elif [ ${MYVAR} = 3 ]; then
    : Third option
fi

->

+ MYVAR=3
+ '[' 3=1 ']'
+ : First option


No comments:

Post a Comment