部分 shell 脚本未执行

部分 shell 脚本未执行

我刚刚开始学习编写 shell 脚本。我的脚本如下:

firefox -new-tab -url google.com -new-tab -url yahoo.com
clear
cd /opt/lampp
sudo ./lampp start
cat somefile

两个新选项卡都会在 Firefox 中打开,然后终端停止进一步执行(尽管 shell 不会返回显示提示,但它仍在运行 Firefox)。如果我按Ctrl+ C,它会终止 Firefox 窗口,终端会返回到初始终端状态。

我该如何重写代码,使所有代码行都能正常工作(我确实希望 Firefox 能先打开)?我做错了什么?

答案1

您需要在脚本第一行的末尾添加与号 (&),或者使用nohup

这个尾部的 & 符号指示 shell 在后台运行命令,也就是说,它会被分叉并作为一项作业在单独的子 shell 中异步运行。shell 将立即返回返回状态 0(表示 true)并继续正常运行,要么处理脚本中的其他命令,要么将光标焦点返回给 Linux 终端中的用户。

nohup捕获挂断信号而 & 符号不会,这意味着当使用 & 运行命令并随后退出 shell 时,shell 将使用挂断信号终止子命令kill -SIGHUP PID,而nohup捕获该信号并忽略它。

所以现在你的脚本看起来像这样:

firefox -new-tab -url google.com -new-tab -url yahoo.com & 
clear
cd /opt/lampp
sudo ./lampp start
cat somefile

正如OP所说最后一个版本(使用nohup):

nohup firefox -new-tab -url google.com -new-tab -url yahoo.com  & 2>/dev/null
clear
cd /opt/lampp
sudo ./lampp start
cat somefile

相关内容