避免在 shell 脚本中使用单独的文件

问题描述

我正在尝试执行以下命令效果很好

我正在执行 test.sh,然后调用 script1.sh。

运行成功,输出如下

applicationuser@servername:/application> sudo ./test.sh
damn,there was an error
timeout happened

两个文件内容如下

test.sh

timeout 10 script1.sh  && echo "timeout not happened" || echo "timeout happened"

script1.sh 如下

if ech "right echo" 2>/dev/null ; then echo 'command was successful'; else echo 'damn,there was an error'; fi

但是当我将两个脚本合并到一个文件(test.sh)中时,如下所示,

test.sh

timeout 10 if ech "right echo" 2>/dev/null ; then echo 'command was successful'; else echo 'damn,there was an error'; fi  && echo "timeout not happened" || echo "timeout happened"

当我执行脚本时会出现如下语法错误

applicationuser@servername:/application> sudo ./test.sh ./test.sh: 行 1: 意外标记附近的语法错误 then' ./test.sh: line 1: timeout 10 if ech "right echo" 2>/dev/null ;然后 echo '命令是 成功的';否则回声'该死的,有一个错误'; fi && 回声 “超时未发生” || echo "超时发生"'

如何去掉script1.sh,把它的内容放到test.sh中执行,不出现语法错误

解决方法

解决方案可能是直接使用 bash 运行命令:

timeout 10 bash -c 'if ech "right echo" 2>/dev/null ; then echo "command was successful"; else echo "damn,there was an error"; fi  && echo "timeout not happened" || echo "timeout happened"'