My knowledge of commandline Bash is missing on a particular area: I constantly forget how to properly escape characters. Today, I wanted to echo this string into a file:
#!/bin/env bash
python -m SimpleHTTPServer
However, this fails:
echo "#!/bin/env bash\npython -m SimpleHTTPServer" > server.sh && chmod +x server.sh
Output:
-bash: !/bin/env: event not found
That's right: Remember to escape !
or Bash will think it's a special Bash event command.
But I can't get the escaping right! \!
yields \!
in the echoed string, and so does \\!
.
Furthermore, \n
will not translate to a line break.
Do you have some general tips that makes it easier for me to understand escaping rules?
To be very precise, which characters should I escape on the Bash command line? Including how to correctly output newline and exclamation mark in my example.
Single quotes inhibit all escaping and substitution:
echo '$hello world!'
You can alternate or disable quoting if you need to mix things up:
echo '$5.00 on '"$horse"'!'
ls -ld ~/'$$'/*
Interpreting escapes is also easy:
echo $'Wake up!\7'
sort -n <<< $'4\n3\n8'