linux運行命令後臺的區別

linux shell中經常會使用後臺運行某個腳本

那麼,下面的幾種區別在哪呢

commandcommand > /dev/nullcommand > /dev/null 2>&1command &command &> /dev/nullnohup command &> /dev/null

下面分別簡單地談一下

# 以test.sh爲例[root@localhost ~]# cat test.sh #!/bin/bash#while [  ‘1’ == ‘1’ ] ;do
	echo `date "+%Y-%m-%d %H:%M:%S"` 
	sleep 100done
command

直接執行,命令輸出會顯示在終端界面上,ctrl-C會終止命令的運行

[root@localhost ~]# bash test.sh 2016-08-07 20:49:47^C
[root@localhost ~]#
command > /dev/null

直接執行,命令標準輸出會定向到null設備,即忽略標準輸出1,但錯誤輸出2會顯示, 其實這等同於command 1 > /dev/null

[root@localhost ~]# cat test.sh#!/bin/bash#while [  ‘1’ == ‘1’ ] ;do
	echo `date "+%Y-%m-%d %H:%M:%S"` 
	ll
	sleep 100done[root@localhost ~]# bash test.sh > /dev/nulltest.sh: line 5: ll: command not found
^C
command > /dev/null 2>&1

這裏首先和上面命令一樣會把1輸出到null設備,2重定向到1,那麼2也會導null設備, 所以所有輸出均送到了null設備

command &

這個想必大家都用過,後臺執行,然而當我們退出終端後,command就會終止 這是因爲我們的終端相當於一個父進程 ,一旦父進程退出,就會給其所有子進程發送hangup信號,子進程收到就會退出。 這裏我不再舉例子 如果我們在頭加上nohup,也就是使用nohup command &,那麼父進程就不會發送hangup給這個子進程,從而會一直在後臺運行

command &> /dev/null 和 command > /dev/null 2>&1區別

網上並沒有說多大區別,這是談到ksh對於後者兼容更好,也就是滿足了需求,所以推薦後者,當然如果確定當前平臺,使用前者似乎更方便少,打了4個字符

後臺控制
# 後臺的命令可以通過jobs查看[root@localhost ~]# jobs[1]-  Running                 bash test.sh &
[2]+  Running                 bash test1.sh &# 調到前後臺可以通過bg %JOB_NUMBER fg %JOB_NUMBER來完成,比如把job 1調到前臺[root@localhost ~]# fg %1bash test.sh# 命令行就會一直持續這樣,ctrl-Z可以讓其停止運行在後臺[root@localhost ~]# fg %1bash test.sh
^Z
[1]+  Stopped                 bash test.sh# 如何讓其後臺運行,因爲現在狀態爲stopped,bg %1,你會發現bg 1也行[root@localhost ~]# bg 1[1]+ bash test.sh &
[root@localhost ~]# jobs[1]-  Running                 bash test.sh &
[2]+  Running                 bash test1.sh &


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章