Linux

在後台執行命令時無法在 shell 腳本中寫入文件

  • September 24, 2018

我有以下需要在 shell 腳本中執行的命令,

nohup command >> help.out & 

當我從終端執行腳本時,nohup命令在後台執行並執行下一個命令,但日誌沒有寫入 help.out 我檢查了文件 help.out 的權限,它們在腳本中創建為只讀,但我使用 chmod -R 777 help.out 更改了權限並且不再是只讀的,仍然沒有寫入 help.out。

我還想知道如何在腳本中創建文件或文件夾,以便它永遠不會是只讀的並且具有所有權限。

#!/bin/bash

trainingState=1
epoch=50


#URL myspace test
URL="xxxxxx"

nohup python3.6 <arguments> >> help.out &

#processId of xyz
processId=$(pidof python3.6)

#this command executes
curl -X POST -H "Content-Type: application/json" -d '{"markdown" : "### The Training has started !! \n > EPOCS:'"$epoch"'"}' $URL

#while loop also executes but no data to read from file 
while [[ $trainingState == 1 ]]; do
     if ps -p $processId > /dev/null ; then
       echo "training happening"
       value=$(tail -n 1 help.out)
       curl requests etc .....
     else
       value=$(tail -n 1 help.out)
       echo "training finished"
       final curl requests etc .....
       trainingState=0
     fi
done

您在後台有程序,並且希望同時將輸出重定向到日誌文件。你必須這樣做:首先將 stdout 發送到你想要它去的地方,然後將 stderr 發送到 stdout 所在的地址:

some_cmd > some_file 2>&1 &

您的程式碼應修改如下:

#!/bin/bash

trainingState=1
epoch=50


#URL myspace test
URL="xxxxxx"

nohup python3.6 <arguments> >> help.out 2>&1 &

#processId of xyz
processId=$(pidof python3.6)

#this command executes
curl -X POST -H "Content-Type: application/json" -d '{"markdown" : "### The Training has started !! \n > EPOCS:'"$epoch"'"}' $URL

#while loop also executes but no data to read from file 
while [[ $trainingState == 1 ]]; do
     if ps -p $processId > /dev/null ; then
       echo "training happening"
       value=$(tail -n 1 help.out)
       curl requests etc .....
     else
       value=$(tail -n 1 help.out)
       echo "training finished"
       final curl requests etc .....
       trainingState=0
     fi
done

更多:1 , 2

引用自:https://unix.stackexchange.com/questions/470968