bash脚本似乎无法执行linux命令

时间:2022-06-05 01:16:27

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.

我正在编写一个bash脚本,假设在循环中自动重启我的autofs。但是当我尝试运行它时,我只是得到一个语法错误。

#./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.

我试过了dos2unix。我用'pwd'替换了第3行来打印我当前的目录,我试图去除/ r,但我仍然得到同样的错误。所以我不确定这里发生了什么。

Has anyone seen this before? Thanks

谁看过这个吗?谢谢

1 个解决方案

#1


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

你有for循环的错误语法。它需要do关键字。

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`:

因为你正在使用bash,所以$(命令)语法比`command`更容易阅读:

for i in $(seq 1 10) ; do

And bash provides a special syntax for simple ranges:

bash为简单范围提供了一种特殊语法:

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.

在循环的身体。 do关键字是该上下文中的语法错误。 shell可能不会报告它,因为先前的语法错误是由循环顶部的缺失do引起的。

#1


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

你有for循环的错误语法。它需要do关键字。

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`:

因为你正在使用bash,所以$(命令)语法比`command`更容易阅读:

for i in $(seq 1 10) ; do

And bash provides a special syntax for simple ranges:

bash为简单范围提供了一种特殊语法:

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.

在循环的身体。 do关键字是该上下文中的语法错误。 shell可能不会报告它,因为先前的语法错误是由循环顶部的缺失do引起的。