I am trying to run a command in a bash file and put the output of command in a variable. But the command must NOT take longer than 2 seconds. I use the command:

timeout -k 2 2 ls /var/log/;

And there is no problem. The command either list the contents of log directory or kills the command in case it took more than two seconds. But when I try to put the output in a variable the commands hangs and doesn't reply or get killed! I use like this:

result=$(timeout -k 2 2 ls /var/log/);

Where is my mistake?

share|improve this question
  • Why would you want to store it in a variable? To store the output of it? I don't see a use where you would need stdout of timeout command– InianFeb 13 at 17:10
  • I want to check weather the result is the contents of the directory or the command has been killed because of the timeout.– Hamid RezaFeb 13 at 17:14

The timeout command will exit with status 124 if it had to kill the process; see here. So you may try something like:

timeout -k 2 2 ls /var/log/ >directory.txtif [ $? -eq 124 ]thenecho "Timeout exceeded!"elsecat directory.txtfi
share|improve this answer

    Your Answer

     
    discard

    By posting your answer, you agree to the privacy policy and terms of service.

    Not the answer you're looking for? Browse other questions tagged or ask your own question.