Wednesday, February 7, 2024

[SOLVED] How to fix my bash script from error: syntax error near unexpected token `done'?

Issue

I am trying to run this bash program in a Centos7 machine. I have tried many different ways but all the time I get this error:

line 31: syntax error near unexpected token `done'
line 31: `done'

Line 31 belongs to the first done.

I did cat -v mybash.bash to check for weird tokens and there are none.

My script is as follows:

for mainFolder in *
do
    if [ -d "${mainFolder}" ]
    then
        cd "${mainFolder}" || exit
        echo "Entering in directory ${mainFolder}" 
        cp ../mypy.py .
        chmod +x mypy.py
        ./mypy.py
        echo "Executing mypy.py"
        sleep 1

        for subFolder in *
        do
            if [ -d "${subFolder}" ]
            then
                cd "${subFolder}" || exit
                echo "Entering in directory $subFolder in $mainFolder"
                echo "Submitting slurm file in current directory"
                sbatch *.slurm
                sleep 1
            fi
            cd ..
        done
    fi
    cd ..
done

Please help me notice what I am doing wrong.


Solution

My guess is that the slurm submission script is not there. The following checks that one and no more than one script is found.

I also moved the cd .. to happen only after a cd.

for mainFolder in *
do
    if [ -d "${mainFolder}" ]
    then
        echo "Entering in directory ${mainFolder}" 
        cd "${mainFolder}" || exit
        cp ../mypy.py .
        chmod +x mypy.py
        echo "Executing mypy.py"
        ./mypy.py
        sleep 1

        for subFolder in *
        do
            if [ -d "${subFolder}" ]
            then
                cd "${subFolder}" || exit
                echo "Entering in directory $subFolder in $mainFolder"
                scripts=$(ls *.slurm)
                nScripts=$(echo $scripts | wc -w)
                if [ $nScripts == 1 ]
                then
                    echo "Submitting $scripts"
                    sbatch $scripts
                elif [ $nScripts == 0 ]
                then
                    echo "Error: No script found"
                else
                    echo "Error: $nScripts scripts found (${scripts})"
                fi
                sleep 1
                cd ..
            fi
        done
        cd ..
    fi
done


Answered By - Colas
Answer Checked By - Senaida (WPSolving Volunteer)