Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine timeout and eval commands in bash

Tags:

bash

timeout

eval

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" ...
like image 811
Wakan Tanka Avatar asked May 12 '15 10:05

Wakan Tanka


People also ask

How do you eval in bash?

`eval` command is used in bash to execute arguments like a shell command. Arguments are joined in a string and taken as input for the shell command to execute the command. `eval` executes the command in the current shell.

Should I use eval in bash?

In the Bash programming language, the eval built-in has a wide range of applications. That is, it can execute other commands, set shell environment, and perform variables substitution and indirection. However, such a powerful tool should be used with care.

What is eval set in bash?

eval is a builtin command of the Bash shell which concatenates its arguments into a single string. Then it joins the arguments with spaces, then executes that string as a bash command.

What is $$ bash?

$$ is a Bash internal variable that contains the Process ID (PID) of the shell running your script.


2 Answers

Simple:

a="echo -e 'a\nb' | wc -l"
eval timeout 10 $a

Output:

2
like image 113
agc Avatar answered Sep 28 '22 13:09

agc


This will work

if timeout "$PROGRAM" "$OPT1" "$OPT2" ... ; then
    echo Program ran successfully
else
    echo Program terminated due to timeout
fi
like image 31
RTLinuxSW Avatar answered Sep 28 '22 15:09

RTLinuxSW