nohup 命令本身沒有直接的超時自動終止功能。但是,你可以結合其他命令來實現這個需求。這里有一個使用 timeout 命令的例子:
timeout 10s nohup your_command &
在這個例子中,your_command 是你想要執行的命令。timeout 命令會在 10 秒后自動終止 your_command。& 符號將命令放入后臺運行。
如果你想要在超時后獲取命令的輸出,可以使用以下方法:
timeout 10s nohup your_command > output.log 2>&1 &
這會將標準輸出和標準錯誤輸出都重定向到 output.log 文件中。
wait 命令:timeout 10s nohup your_command > output.log 2>&1 &
timeout_pid=$!
wait $timeout_pid
if [ $? -eq 124 ]; then
echo "Command timed out"
else
echo "Command completed successfully"
fi
這個例子中,我們將 nohup 命令放入后臺運行,并將其進程 ID 存儲在 timeout_pid 變量中。然后,我們使用 wait 命令等待該進程結束。如果進程因為超時而終止,wait 命令會返回 124,我們可以根據這個返回值判斷命令是否超時。