簡體   English   中英

為什么超時在bash腳本中不起作用?

[英]Why does timeout not work within a bash script?

如果超過幾秒鍾,我試圖殺死一個進程。

當我在終端中運行它時,以下工作正常。

timeout 2 sleep 5

但是當我有一個腳本時 -

#!/bin/bash
timeout 2 sleep 5

它說

超時:找不到命令

為什么這樣? 解決方法是什么?

- 編輯 -

在執行類型超時時,它說 -

timeout是一個shell函數

看來你的環境$PATH變量不包含/usr/bin/ path或者可能是其他地方存在timeout二進制。

所以只需檢查超時命令的路徑:

command -v timeout

並在腳本中使用絕對路徑

防爆。

#!/bin/bash
/usr/bin/timeout 2 sleep 5

更新1#

根據您的更新,它是在shell中創建的功能。 您可以在腳本中使用絕對路徑,如上例所示。

更新2# timeout命令Coreutils的版本=>添加8.12.197-032bb ,如果GNU超時不可用,你可以使用預期(的Mac OS X,BSD,......通常不具有默認的GNU工具和實用程序)。

################################################################################
# Executes command with a timeout
# Params:
#   $1 timeout in seconds
#   $2 command
# Returns 1 if timed out 0 otherwise
timeout() {

    time=$1

    # start the command in a subshell to avoid problem with pipes
    # (spawn accepts one command)
    command="/bin/sh -c \"$2\""

    expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"    

    if [ $? = 1 ] ; then
        echo "Timeout after ${time} seconds"
    fi

}

例:

timeout 10 "ls ${HOME}"

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM