【问题标题】:Avoid seperate file in shell script避免在 shell 脚本中使用单独的文件
【发布时间】:2021-05-08 12:01:28
【问题描述】:

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

我正在执行 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 ' 命令是 成功的'; else echo '该死,出现错误';菲 && 回声 “没有发生超时” || echo "发生超时"'

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

【问题讨论】:

  • timeout 基本上执行您作为子进程提供的外部命令,not 在子shell 中。由于没有名为if 的可执行文件,它不起作用。出于同样的原因,alias foo=ls; timeout 10 foo 也不起作用。

标签: linux bash shell unix scripting


【解决方案1】:

解决方案可以直接使用 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"'

【讨论】:

  • 感谢它为消除 script1.sh 工作,我为使超时工作超时 10 bash -c 'sleep 11; if ech "右回声" 2>/dev/null ;然后回显“命令成功”; else echo "该死,出现错误"; fi' && echo "没有发生超时" ||回声“发生超时”,感谢您的想法!
猜你喜欢
  • 2017-10-24
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多