运行 bash 默认在后台运行脚本
Run bash script in background by default
我知道我可以使用 bash script.sh & disown
或者 nohup
在后台 运行 我的 bash 脚本。但是,我想 运行 默认情况下我的脚本在后台运行,所以当我 运行 bash script.sh
或使其可执行后,通过 运行ning ./script.sh
它默认情况下应该 运行 在后台。我怎样才能做到这一点?
只需编写一个包装器,用 nohup actualScript.sh &
调用您的实际脚本。
包装脚本wrapper.sh
#! /bin/bash
nohup ./actualScript.sh &
actualScript.sh
中的实际脚本
#! /bin/bash
for i in {0..10}
do
sleep 10 #script is running, test with ps -eaf|grep actualScript
echo $i
done
tail -f 10 nohup.out
0
1
2
3
4
...
独立解决方案:
#!/bin/sh
# Re-spawn as a background process, if we haven't already.
if [[ "" != "-n" ]]; then
nohup "[=10=]" -n &
exit $?
fi
# Rest of the script follows. This is just an example.
for i in {0..10}; do
sleep 2
echo $i
done
if 语句检查是否传递了 -n
标志。如果没有,它会调用自己 nohup
(解除调用终端的关联,因此关闭它不会关闭脚本)和 &
(将进程置于后台,return 到迅速的)。然后父级退出以将后台版本留给 运行。后台版本是使用 -n
标志显式调用的,因此不会导致无限循环(这很难调试!)。
for 循环只是一个例子。使用 tail -f nohup.out
查看脚本的进度。
请注意,我将此答案与 this and this 拼凑在一起,但都不够简洁或完整,无法重复。
添加到 Heath Raftery 的 ,对我有用的是他建议的变体,例如:
if [[ "" != "-n" ]]; then
[=10=] -n & disown
exit $?
fi
我知道我可以使用 bash script.sh & disown
或者 nohup
在后台 运行 我的 bash 脚本。但是,我想 运行 默认情况下我的脚本在后台运行,所以当我 运行 bash script.sh
或使其可执行后,通过 运行ning ./script.sh
它默认情况下应该 运行 在后台。我怎样才能做到这一点?
只需编写一个包装器,用 nohup actualScript.sh &
调用您的实际脚本。
包装脚本wrapper.sh
#! /bin/bash
nohup ./actualScript.sh &
actualScript.sh
中的实际脚本#! /bin/bash
for i in {0..10}
do
sleep 10 #script is running, test with ps -eaf|grep actualScript
echo $i
done
tail -f 10 nohup.out
0
1
2
3
4
...
独立解决方案:
#!/bin/sh
# Re-spawn as a background process, if we haven't already.
if [[ "" != "-n" ]]; then
nohup "[=10=]" -n &
exit $?
fi
# Rest of the script follows. This is just an example.
for i in {0..10}; do
sleep 2
echo $i
done
if 语句检查是否传递了 -n
标志。如果没有,它会调用自己 nohup
(解除调用终端的关联,因此关闭它不会关闭脚本)和 &
(将进程置于后台,return 到迅速的)。然后父级退出以将后台版本留给 运行。后台版本是使用 -n
标志显式调用的,因此不会导致无限循环(这很难调试!)。
for 循环只是一个例子。使用 tail -f nohup.out
查看脚本的进度。
请注意,我将此答案与 this and this 拼凑在一起,但都不够简洁或完整,无法重复。
添加到 Heath Raftery 的
if [[ "" != "-n" ]]; then
[=10=] -n & disown
exit $?
fi