我有几个列表,想对它们运行一些命令。由于列表很长,我想并行运行这些命令,因此使用nohup
.
对于每个项目,我尝试使用echo
包含 nohup 命令的循环,但它不起作用 -cat another_list_of_names
读取到 stdout,但不读取到./tools
.首先cat
infor a in $(cat list_of_names)
将列表发送到循环,但echo
'edfor b in $(cat another_list_of_names)
将其发送到 stdout。
如何设置这些 nohup 命令并行运行(是否可以使用 运行nohup
)echo
?
for a in $(cat list_of_names)
do
ID=`echo $a`
mkdir ${ID}
echo "
nohup sh -c '
for b in $(cat another_list_of_names)
do
./tools $b $a >> ${ID}/output
done' &
"
done
答案1
我对您的代码做了一些改进:
# This sort of loop is generally preferable to the one you had.
# This will handle spaces correctly.
while read a
do
# There's no need for the extra 'echo'
ID="$a"
# Quote variables that may contain spaces
mkdir "$ID"
# This is a matter of taste, but I generally find heredocs to be more
# readable than long echo commands
cat <<EOF
nohup sh -c '
while read b
do
# Quotation marks
./tools \$b $a >> "${ID}/output"
done < another_list_of_names' &
EOF
done < list_of_names
答案2
您似乎对什么感到困惑echo
。你不能跑任何命令使用echo
,不具体nohup
。echo
只是显示文本,并不执行它。
现在,如果我明白你想要正确做什么,你所需要的就是这样:
#!/usr/bin/env bash
## As others have said, this is a better loop for your purposes
## and it avoids both useless uses of cat.
while read a
do
## you don't need to copy the variable; you need the
## quotes to cope with names with spaces.
mkdir "$a"
while read b
do
nohup ./tools $b $a >> "$a"/output &
done < another_list_of_names
done < list_of_names
答案3
我不太确定我明白你想要什么。只是猜测:以下代码片段之一是否执行了预期的操作?
for a in $(cat list_of_names)
do
ID=`echo $a`
mkdir ${ID}
echo '
nohup sh -c '\''
for b in $(cat another_list_of_names)
do
./tools $b $a >> ${ID}/output
done'\'' &
'
done
或者
for a in $(cat list_of_names)
do
ID=`echo $a`
mkdir ${ID}
echo "
nohup sh -c '
for b in $(cat another_list_of_names)
do
./tools \$b $a >> ${ID}/output
done' &
"
done
答案4
您是否想回显此内容以查看最终命令的样子?或者您是否尝试实际尝试nohup
使用该 echo 来运行该命令?
我建议将该行添加到脚本的顶部,set -x
以便您可以看到每一行正在做什么,而不是仅仅通过查看来尝试理解它。
您set -x
也可以根据需要在脚本中打开:
set -x
... code to debug ...
set +x