首页 > 解决方案 > 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打开多个窗口,但我似乎也无法做到这一点。

标签: bashshelldockerhadoop-yarncd

解决方案


我认为您打算将每个子命令置于后台。为此,您需要在每个命令的末尾添加一个 & 符号。如果这些子进程正在写入 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!!"

注意:如果任何子进程尝试从终端读取输入,那么它们将挂起。


推荐阅读