linux shell script let: not found

Today I was writing a shell script when I came across this issue. In one part of the shell script I needed to count the number of lines I read from an input file, this is where I used 'let'.
Following is the concerned sample code of my script:

#!/bin/sh

#Taking up the first command line argument as the file name
filename=$1
echo "Using file" $filename

#Next to read the file line by line and dump the output
count=0
cat $filename | while read LINE
do
        let count++            //I use 'let' here
        echo $count $LINE
done

echo -e "\nTotal "$count "lines read."
When I run this script I got following error for every time this line was encountered in the loop in the script:
fnr.sh: 11: fnr.sh: let: not found
Reason:
        This happened because 'let' command is a bash builtin. As indicated in my post /bin/sh: Illegal option -h, the default shell in Ubuntu is mostly dash and not bash. So when we write '#!/bin/sh' on top of the script by default it gets interpreted using dash and not bash.

Solution:
         For making bash as the default interpreter, one needs to run the following command: (*)

sudo dpkg-reconfigure dash
<password>
and when you get the option select "no" to actually use bash instead of dash.
*NOTE: This will make bash as the default shell for all your scripts. Unless you want otherwise, please do not use this!

Happy scripting!

1 comment: