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?


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 &
  • Bonus points if you pipe the echo string to the wall command, all logged in users will get it in their tty ;-) – Jake Apr 1 '15 at 20:46

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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