D.Zou
D.Zou

Reputation: 808

bash script can't seem to execute linux commands

I am writing a bash script that is suppose to auto restart my autofs in a loop. but when I try to run it I just get a syntax error.

#./dd_nfs.sh
./dd_nfs.sh: line 3: syntax error near unexpected token `/etc/init.d/autofs'
./dd_nfs.sh: line 3: `/etc/init.d/autofs reload'

# cat dd_nfs.sh
    #!/bin/bash
    for i in `seq 1 10`
    /etc/init.d/autofs reload
    sleep 5
    echo "read test"
    do time echo "read"
    echo "read test done"
    done

I tried the dos2unix. I replaced line 3 with just 'pwd' to print my current dir and I tried to strip out the /r but I still get the same error. So I am not sure what's going here.

Has anyone seen this before? Thanks

Upvotes: 0

Views: 75

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263617

You have the wrong syntax for the for loop. It requires the do keyword.

Change this:

for i in `seq 1 10`

to this:

for i in `seq 1 10` ; do

Or, if you prefer, you can write it like this:

for in in `seq 1 10`
do
    # body of loop
done

(Also, indenting your code would make it easier to read.)

Since you're using bash, the $(command) syntax is IMHO easier to read than `command`:

for i in $(seq 1 10) ; do

And bash provides a special syntax for simple ranges:

for i in {1..10} ; do

In response to your latest edit, you added this line:

do time echo "read"

in the body of the loop. The do keyword is a syntax error in that context. The shell might not report it because of the previous syntax error caused by the missing do at the top of the loop.

Upvotes: 2

Related Questions