Bash – “Syntax error: Bad for loop variable” when trying to run awk in a loop in a shell script

awkbashshell

I have an awk command which runs well on terminal: this awk command creates different file according to their column header.
awk command:

for((i=2;i<5;i++)); do 
    awk -v i=$i 'BEGIN{OFS=FS="\t"}NR==1{n=$i}{print $1,$i > n".txt"}' ${Batch}.result.txt
done

the same command when incorporated in a shell script shows error:

Syntax error: Bad for loop variable

It worked the following way. I tried with she-bang as suggested but it repeated the error.

for i in 2 3 4; do awk -v i=$i 'BEGIN{OFS=FS="\t"}NR==1{n=$i}{print $1,$i  n".txt"}'

Best Answer

I don't think the error has anything to with your Awk command. I think you are running it in the POSIX bourne shell sh in which for-loop construct with (( is not supported.

Run the script with shebang set to the path where bash is installed. Usually it is safe to do #!/usr/bin/env bash because #!/usr/bin/env searches PATH for bash, and bash is not always in /bin, particularly on non-Linux systems. For on a OpenBSD system, it's in /usr/local/bin.

Related Question