4

In Bash in the terminal, it is impossible to run a command that ends with and & (being sent to the background) followed by another command (obviously with a ; between them). Why is that? Why can't you run anything with &; or $ ; in it?

I'm trying to recreate a 502 error and was trying to DoS a specific page in a testing server. I was trying to run this:

while true; do curl -s https://some.site.com/someImage.jpg > /dev/null &; echo blah ; done

as a "one-liner" in the terminal. However, I got this error:

-bash: syntax error near unexpected token `;'

However the commands work individually, and when I run the curl command not in the background it works as a loop as well. It also works when it write a one line script, "/tmp/curlBack.sh" that includes only

curl -s https://some.site.com/someImage.jpg > /dev/null &

And then run

while true; do bash /tmp/curlBack.sh ; echo blah ; done

Why am I getting this error and how do I fix it?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Uberhumus
  • 921
  • 1
  • 13
  • 24
  • 2
    Does this answer your question? [How do I run multiple background commands in bash in a single line?](https://stackoverflow.com/questions/14612371/how-do-i-run-multiple-background-commands-in-bash-in-a-single-line) – Ruud Helderman May 31 '20 at 11:37
  • @RuudHelderman, Not as far as I saw. I wanted to know why this was happening, not how to to work around it. What PalaceChan asked is how to do it. And the answers they got were respectively not why this happens but how to work around it. These questions are indeed very related but not identical. – Uberhumus May 31 '20 at 11:54

1 Answers1

9

The problem is with the semi-colon after the ampersand (&):

An ampersand does the same thing as a semicolon or newline in that it indicates the end of a command, but it causes Bash to execute the command asynchronously. BashSheet

Basically, it's as if you were to put double semi-colons back to back, that would cause a syntax error too.

To fix this problem, you simply need to remove the semi-colon, I tested it that way and it seems to be working:

while true; do curl -s https://some.site.com/someImage.jpg > /dev/null & echo blah ; done
Mike Elahi
  • 1,103
  • 1
  • 13
  • 28