How to combine timeout and eval commands in bash

送分小仙女□ 提交于 2019-12-23 09:57:30

问题


For executing command that is stored in variable the eval command is used:

└──> a="echo -e 'a\nb' | wc -l"
└──> eval $a
2

But how can it be combined with timeout command? I've tried following which gives me wrong output:

└──> timeout 10 $a
'a
b' | wc -l

And the following which gives me errors:

└──> timeout 10 "$a"
timeout: failed to run command `echo -e \'a\\nb\' | wc -l': No such file or directory

└──> timeout 10 $(eval $a)
timeout: failed to run command `2': No such file or directory

└──> timeout 10 $(eval "$a")
timeout: failed to run command `2': No such file or directory

The question can also stand: How can I be sure that following command is executed properly?

timeout 10 "$PROGRAM" "$OPT1" "$OPT2" ...

回答1:


This will work

if timeout "$PROGRAM" "$OPT1" "$OPT2" ... ; then
    echo Program ran successfully
else
    echo Program terminated due to timeout
fi



回答2:


If it's about keeping commands in variables, this will work, although don't know if it's a 'proper bash way' to do it:

command.sh:

#!/bin/bash
echo -e 'a\nb' | wc -l

run.sh:

#!/bin/bash
a="command.sh"
timeout 10 ./$a



回答3:


echo "$(timeout 10 echo -e 'a\nb' | wc -l)"
OR
echo "$(timeout 2 echo "$(eval $a)")"

explanation 1 here : HERE

explanation 2 here : HERE




回答4:


Simple:

eval timeout 10 $a

Output:

2


来源:https://stackoverflow.com/questions/30188547/how-to-combine-timeout-and-eval-commands-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!