Bash,timeout' ls | wc -l'

时间:2016-09-03 19:59:39

标签: bash timeout

我搜索了这个网站并谷歌如何超时bash命令,如果它需要很长时间运行,并尝试了多种不同的方法,似乎无法让任何工作。

具体来说,我需要超时' ls | wc -l'如果运行时间超过10秒;但是,我将运行' ls | wc -l'在多个目录上,如果只需要一秒钟就完成,不要等待10秒钟。

我试图遵循这似乎只是一种工作,但我还是要等到完整的10秒时,' ls | wc -l'在10秒睡眠前完成。

ls /file/path/to/count/ | wc -l &
pidsave=$!
sleep 1
if [ -e /proc/$pidsave ]; then
kill $pidsave; echo $?
echo 'ls command was timed out'
else
echo 'ls command completed'
fi

3 个答案:

答案 0 :(得分:0)

您可以使用timeout命令:

if timeout 10 ls /file/path/to/count/ | wc -l; then
    echo "Successful!!"
else
    echo "Timed Out!!"
fi

检查man timeout

答案 1 :(得分:0)

之前发布的回答对我来说也不起作用。 问题在于if测试wc -l的结果,而不是实际的timeout

为避免这种情况,你可以将命令包装在一个函数中,将命令放入一个可删除的文件中,或者取消链接命令并单独执行它们,具体取决于你实际需要对你的输出做什么。上下文。

选项1 - 功能

该函数必须导出到子shell,然后在子shell下执行。

#!/bin/bash
function my_ls {
    ls | wc -l
}

export -f my_ls
timeout 10 bash -c my_ls
if [ $? -eq 0 ]; then
    echo "cmd finished in time"
else
    echo "cmd did NOT finish in time"
fi

选项2 - 文件

ls | wc -l放入某个文件(例如/tmp/ls.sh)并使其可执行(chmod +x /tmp/ls.sh)。使用该文件作为timeout命令的参数:

#!/bin/bash
MY_FILE="/tmp/ls.sh"
echo "ls | wc -l" > $MY_FILE
chmod +x $MY_FILE

timeout 10 $MY_FILE
if [ $? -eq 0 ]; then
    echo "cmd finished in time"
else
    echo "cmd did NOT finish in time"
fi

选项3 - 未链接

假设ls是在此示例中需要花费很长时间才能完成的命令,请先运行该命令。可能的输出存储在一个变量中(假设命令没有超时),您可以随后使用它:

#!/bin/bash
LIST="$(timeout 10 ls)"
if [ $? -eq 0 ]; then
    echo "cmd finished in time"
    echo $(wc -l <<< $LIST)
else
    echo "cmd did NOT finish in time"
fi

答案 2 :(得分:0)

在Jiri的帮助下,选项3成功了。这是我正在使用的确切代码,以防任何人感兴趣。我将它包装在for语句中,并以浅蓝色提供了Count的标题,TIMED OUT !!!在红色,实际计数在绿色。

echo -e "\e[1;4;36mCount\e[0m" >> $LOGPATH
for c in $DIR1 $DIR2 $DIR3 $DIR4; do

LIST=$(timeout 2 ls $c &>/dev/null; echo $?)
if [ $LIST != 0 ]; then
    echo -e $c "\e[1;31mTIMED OUT!!! \e[0m" >> $LOGPATH
else
  echo -e $c "\e[1;32m$(ls $c |wc -l) \e[0m" >> $LOGPATH
fi

done