syntax error near unexpected token `do

11,889

Your script is DOS encoded and sh / bash do not like this. Install dos2unix and run

dos2unix <script>

on your script. And run it again.

Share:
11,889

Related videos on Youtube

Flyout
Author by

Flyout

Updated on September 18, 2022

Comments

  • Flyout
    Flyout almost 2 years

    I have a "syntax error near unexpected token `do" error, using a for loop in a .sh. Here is the code :

    #!/bin/sh
    
    # some code
    
    for flux in $(ls -d /home/eai/*/*/*) ; do
      FICHIER=$(ls -p -tr $flux | grep -v / | head -n 1)
      if [[ $FICHIER ]] ; then
         # some code
      fi
    done
    

    Different ways to execute the script, and the output :

    1) sh script.sh or bash script.sh

    'cript_1409.sh: line 24: syntax error near unexpected token `do
    'cript_1409.sh: line 24: `for flux in $(ls -d /home/eai/*/*/*); do
    

    2) ./script.sh

    -bash: ./script_1409.sh: /bin/sh^M: bad interpreter: No such file or directory
    

    What I tried :

    1) Use different syntax for the loop.

    for flux in $(ls -d /home/eai/*/*/*) ; do
      FICHIER=$(ls -p -tr $flux | grep -v / | head -n 1)
      if [[ $FICHIER ]] ; then
         # some code
      fi
    ) &
    done
    

    or

    for flux in $(ls -d /home/eai/*/*/*)
    do
      FICHIER=$(ls -p -tr $flux | grep -v / | head -n 1)
        if [[ $FICHIER ]] ; then
          # some code
        fi
    done
    

    2) Change the #!/bin/sh to #!/bin/bash.

    3) Change the extension .sh to .bash and retry all the execution commands aforementioned.