【问题标题】:When using exec with &, the final command does not run将 exec 与 & 一起使用时,最终命令不会运行
【发布时间】:2019-04-11 22:15:15
【问题描述】:

if/fi 之后的代码似乎没有运行。这是我所拥有的:

我有一个脚本,/my/scripts/dir/directoryPercentFull.sh:

directoryPercentFull="$(df | grep '/aDir/anotherDir' | grep -o '...%' | sed 's/%//g' | sed 's/ //g')"
if [ $directoryPercentFull -gt 90 ]
then
    echo $directoryPercentFull
    exec /someDir/someOtherDir/test01.sh &
    exec /someDir/someOtherOtherDir/test02.sh &
    exec /someDir/yetAnotherDir/test03.sh
fi

echo "Processing Done"

被调用的脚本是: /someDir/someOtherDir/test01.sh

#!/usr/bin/env bash
echo "inside test01.sh"
sleep 5
echo "leaving test01.sh"

/someDir/someOtherOtherDir/test02.sh

#!/usr/bin/env bash
echo "inside test02.sh"
sleep 5
echo "leaving test02.sh"

/someDir/yetAnotherDir/test03.sh

#!/usr/bin/env bash
echo "inside test03.sh"
sleep 5
echo "leaving test03.sh"

通过 cd-ing 到 /my/scripts/dir 运行脚本,然后执行 ./directoryPercentFull.sh 给出: 输出:

93
inside test03.sh
inside test02.sh
inside test01.sh
leaving test03.sh
leaving test01.sh
leaving test02.sh

预期输出:

93
inside test01.sh
inside test02.sh
inside test03.sh
leaving test01.sh
leaving test02.sh
leaving test03.sh
Processing Done

echo 命令的顺序没什么大不了的,但如果有人知道他们为什么走 3,2,1,然后是 3,1,2,我不会讨厌解释。

但是,我没有得到最后的Processing Done。任何人都知道为什么最后的echo 回到/my/scripts/dir/directoryPercentFull.sh 不会发生?我故意不在最后一个exec 语句之后放置&,因为我不希望if/fi 之后的内容在所有处理完成之前运行。

【问题讨论】:

  • 您的问题可以简化为exec echo 1; echo 2。
  • 你不需要用exec来运行命令,去掉这些exec,从每一行开始,直接调用脚本。
  • @melpomene,我确实认为我对 exec 所做的事情有所了解。我在 stackoverflow 上找到了这个,并认为这样做是有效的:Run bash script from another script without waiting for script to finish executing?
  • 链接的答案恰好起作用,因为 &-less exec 是脚本中的最后一个命令。它不应该有那些execs,回答者应该提到它。

标签: bash unix


【解决方案1】:
/someDir/someOtherDir/test01.sh &
/someDir/someOtherOtherDir/test02.sh &
/someDir/yetAnotherDir/test03.sh

摆脱所有execs。 exec 导致 shell 进程被给定命令替换,这意味着 shell 不会继续执行进一步的命令。

echo 命令的顺序没什么大不了的,但如果有人知道他们为什么要 3,2,1,然后是 3,1,2,我不会讨厌解释。

打印输出可以按任何顺序排列。这三个脚本在并行进程中运行,因此不知道它们echo 打印输出的顺序。

【讨论】:

  • @RoryLatham, ...正如约翰所说,输出是无序的;仅仅因为输出排序在一次运行中以给定的方式出现(或在给定的系统负载水平下执行的一组运行中)并不意味着它会以一致的方式运行。这就像 Python 中的字典顺序;如果您正在测试一种特定的方式,它可能看起来一致,但如果它不能保证一致,那么编写假设其他方式的代码将会对您不利。
猜你喜欢
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多