Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to do this as an April Fool's prank: make a linux machine display a message in the shell every few seconds.

My thought is to achieve this by starting an infinite loop that runs as a background job (in .bashrc).

For example, this does what I want:

while true ; do echo Evil Message; sleep 10; done

In order to run it in background I tried:

cmd="while true ; do echo Evil Message; sleep 10;"
$cmd &

but this fails with the error:

while: command not found

Why do I get the error? Is there a way to make this script work?

share|improve this question

2 Answers 2

up vote 15 down vote accepted

while is not a command, it's a shell keyword. Keywords are recognised before variable expansion happens, so after the expansion, it's too late.

You have several options:

  1. Don't use a variable at all.

    while true ; do echo Evil Message; sleep 10; done &
    
  2. Use eval to run the shell over the expanded value of the variable

    eval "$cmd" &
    
  3. Invoke a shell to run the loop

    bash -c "$cmd" &
    
  4. Use a function (that's what is typically used to store code):

    cmd() { while true ; do echo Evil Message; sleep 10; done; }
    cmd &
    
share|improve this answer
    
Bonus points if you pipe the echo string to the wall command, all logged in users will get it in their tty ;-) –  Jake yesterday

Another option (besides all the good options listed in choroba's answer) would be to run it in a subshell, like this:

(while true; do echo Evil Message; sleep 10; done;) &

This will cause bash to run another instance of itself running your code, in the background.

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.