bash - cd 进入多个目录并运行命令
问题描述
试图用 shell 脚本自动化一些东西..
操作系统:Mac
想要实现这样的目标:
脚本.sh
cd foo
yarn start
cd ..
cd bar
yarn start
cd ..
cd foobar
./start.sh
cd ..
cd boofar
docker-compose up
cd ..
echo "Go to your localhost and see your webapp working!!"
但这些命令在我点击^C
.
这样的事情甚至可能吗?我尝试使用&&
,;
等等,但似乎找不到正确的组合。此外,查看screen
打开多个窗口,但我似乎也无法做到这一点。
解决方案
我认为您打算将每个子命令置于后台。为此,您需要在每个命令的末尾添加一个 & 符号。如果这些子进程正在写入 stdout/stderr,您应该在它们前面加上 'nohup' 并将输出重定向到某种形式的日志文件:
#!/bin/bash
cd foo
nohup yarn start > {/log/file1} &
cd ..
cd bar
nohup yarn start > {/log/file2} &
cd ..
cd foobar
nohup ./start.sh > {/log/file3} &
cd ..
cd boofar
nohup docker-compose up > {/log/file4} &
cd ..
echo "Go to your localhost and see your webapp working!!"
您还可以将通用功能放在一个函数中,以使整个脚本更具可读性:
#!/bin/bash
function start_child() {
cd "${1}"
logfile="${2}"
shift 2
nohup "${@}" > ${logfile} &
cd ..
}
start_child foo /log/file1 yarn start
start_child bar /log/file2 yarn start
start_child foobar /log/file3 ./start.sh
start_child boofar /log/file3 docker-compose up
echo "Go to your localhost and see your webapp working!!"
注意:如果任何子进程尝试从终端读取输入,那么它们将挂起。
推荐阅读
- java - 如何使用按钮搜索将搜索查询传递给另一个活动
- javascript - 如何将道具传递给 React Navigation 导航器中的组件?
- mysql - Mysql插入来自我母语的字符的问题
- java - 如何使用 Mockito 和 JUnit 定义由链依赖调用的方法的行为?
- wordpress - Wordpress 可视化编辑器不工作 4.9.6 - 在编辑器中获取跨度代码
- c# - Unity 2D Game Kit 图像更改为暖色?
- angular - 验证消息总是显示在 Angular5 中,即使文本框有一些值
- ruby - Chromedriver 不允许在 Windows 上使用 jruby 的无头模式 - Childprocess 错误
- intellij-idea - 客户端项目在 IntelliJ 中访问 Akka Actor 的依赖项
- react-native - React Native上隐藏选项卡时如何让视图绘制空白部分?