[syntax] How can I split a shell command over multiple lines when using an IF statement?

How can I split a command over multiple lines in the shell, when the command is part of an if statement?

This works:

if ! fab --fabfile=.deploy/fabfile.py --forward-agent --disable-known-hosts deploy:$target; then rc=1                                                                       
fi

This doesn't work:

# does not work:
if ! fab --fabfile=.deploy/fabfile.py \ 
  --forward-agent \
  --disable-known-hosts deploy:$target; then   
  rc=1
fi

Instead of the whole command executing, I get:

./script.sh: line 73: --forward-agent: command not found

More importantly, what is missing from my understanding of Bash that will help me understand this and similar issues in the future?

This question is related to syntax sh

The answer is


For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).