首页 > 解决方案 > Bash 运行两个命令都依赖于第一个

问题描述

我确定有人问过这个问题,但我的搜索没有结果。

我想按顺序运行 3 个 bash 命令,第二个和第三个仅在第一个成功的情况下运行。

例子:

## Setup
mkdir so_test_tmp && cd so_test_tmp
echo "This is something" > something
cd ..

## Example commands
cd so_test_tmp ??? cat nothing ??? cd ..    # 0.
cd so_test_tmp ??? cat something ??? cd ..  # 1.
cd does_not_exist ??? cat nothing ??? cd .. # 2.

这三个命令应始终以 PWD 结尾。在0.第一个 cd 中运行,然后是最后一个。在1.所有三个命令中成功运行。在2.第一个命令中失败,所以第二个和第三个没有运行。

标签: bash

解决方案


关于什么?

pushd .; cmd1 && cmd2 && ... cmdn; popd
  • pushd .保存您当前的目录。
  • 然后你执行你的命令;你使用&&这样,如果一个失败,其他人不会被执行。
  • popd回到你的初始目录。

编辑:关于您在下面的评论,是的,这个pushd .; popd结构很愚蠢;它让您忘记每组命令的执行情况。

pushd .; cd so_test_tmp && cat nothing; popd; # 0.
pushd .; cd so_test_tmp && cat something; popd; # 1.
pushd .; cd does_not_exist && cat nothing; popd; # 2.
  • 运行三组命令后,您在原始目录中完成。
  • 在每组命令中,每当一个命令失败时,它都会缩短后面其他命令的执行(请参阅它们由 分隔&&)。

如果您需要知道每组命令是否成功,您可以随时测试执行结果(并在运行以下命令集之前转到您的初始目录并再次保存):

pushd .;
cd so_test_tmp && cat nothing && cd .. ; # 0.
test $? -eq 0 || (popd; pushd .) ;
cd so_test_tmp && cat something && cd ..; # 1.
test $? -eq 0 || (popd; pushd .) ;
cd does_not_exist && cat nothing && cd ..; # 2.
test $? -eq 0 || (popd; pushd .) ;

推荐阅读