Shell script: syntax error: bad for loop variable error resolution

A simple shell script is written in Linux Mint, using for.. do.. Done 1+2+3…… +100 value, the result of “SH-n XXx. sh” syntax detection is always wrong, but can run normally on PC;

Script:

#!/bin/bash
#information
 
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
 
read -p "Please input a num " num
sum=0
for ((a=0; a<=$num; a++))
do 
sum=$(($sum + $a))
done
echo "the sum is ==> $sum"
exit 0

The errors are as follows:

Syntax error: Bad for loop variable

Analysis:
Since ubuntu 6.10, ubuntu has replaced the previous default bash shell with the dash shell; This appears as the /bin/sh link inverted /bin/dash instead of the traditional /bin/bash.

allen@allen-lql ~/workspace/script $ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Aug 12 14:29 /bin/sh -> dash

So when using SH to perform the detection, dash is actually used, and DASH does not support this C-format for loop writing.

Solutions:
1, change the default shell to bash. (Bash supports for loop in C format)

sudo dpkg-reconfigure dash

choose No

2. Use bash detection directly:

bash -n xxx.sh

3. To ensure the portability of shell scripts, directly change shell scripts and use the for loop format supported by the shell:

for a in `seq $num`


Read More: