bash - 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.
第一个命令中失败,所以第二个和第三个没有运行。
解决方案
关于什么?
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 .) ;
推荐阅读
- node.js - TypeORM CLI 与 type-graphql 一起使用时不会生成迁移
- vbscript - 用于 shift+Break 的 vbscript sendkeys
- javascript - 如何使用javascript根据选项卡选择更改下拉菜单
- python - 在python中将unicode文本写入HTML
- android - 像在 RecyclerView 中一样为 LinearLayout 拖动选择
- javascript - 如何调试此加权随机名称选择器代码
- java - java - 如何在Java中使用硒单击Excel工作表中的按钮
- php - 如何在没有键 Laravel 的情况下对集合进行分页
- typescript - Firebase 获取数据 ionic4
- ios - URLCache 和驱逐控制