我试图在后台运行程序。有没有办法通过控制操作员可选。喜欢的东西:控制运算符作为bash脚本中的可选参数
if some_condition
bg=&
fi
myprog $bg
然而,我所看到的,是bash(正确)处理$bg
作为参数传递给myprog
。我试图在后台运行myprog
。
有没有办法做到这一点?
我试图在后台运行程序。有没有办法通过控制操作员可选。喜欢的东西:控制运算符作为bash脚本中的可选参数
if some_condition
bg=&
fi
myprog $bg
然而,我所看到的,是bash(正确)处理$bg
作为参数传递给myprog
。我试图在后台运行myprog
。
有没有办法做到这一点?
如何:
if some_condition
then
myprog &
else
myprog
fi
我已经这样做了。但是,想知道是否有办法在没有条件检查的情况下在一行中处理这个问题。 –
如果您的意图是只指定'myprog',那么我在下面添加了一个解决方案,但是,如果您只运行一次'myprog',那么James的回答将更可取。 –
我同意詹姆斯·布朗的回答,但是,如果你只希望一次指定myprog
,那么也许你可以使用一个函数来确定它应该运行在后台或没有。但是,这并不意味着你会在最初编写更多行,但如果你正在运行可能有很多的背景,你可以从中受益......
run_in_background=false
run_cmd() {
echo "Running [email protected]"
if $run_in_background; then
"[email protected]" &
else
"[email protected]"
fi
}
if [[ "$1" == '--bg' ]]; then
run_in_background=true
shift
fi
run_cmd "[email protected]"
然后你就可以像这样运行:
./script.bash --bg sleep 1
或者,如果你可以在脚本本身运行:
... (Continuing from inside the script above)
run_cmd sleep 1
run_cmd echo hello
wait # Waits for background processes to finish
然后你就可以决定是否在传递给run_cmd
的命令将在前台或backgro通过省略或使用--bg
标志。
'eval myprog $ bg'? – Cyrus
为什么不“如果some_condition;然后myprog&; fi”?否则,你可以使用eval。 – codeforester
我打算建议'eval',但'eval'是'evil'。使用和if语句会更容易和更安全。 –