0

I am trying to print #!/ via Bash, but it doesn't print it and instead prints the following.

parth@parth-ubuntu64:$ echo "#!\/"
bash: !\/: event not found

EDITED: Allow me to make one more update. How do you make the following work? I think I should just use python instead of bash. The reason why I am trying to do this is because, I want to pipe this into a file which requires sudo permission. This is the only way I can execute sudo => sudo sh -c " echo something > file "

sh -c 'echo \'#!/bin/bash \' '
Parth
  • 523
  • 1
  • 7
  • 21

5 Answers5

4

Within double quotes (and with history expansion enabled), the ! has special meaning. To print those characters literally, use single quotes instead of double:

$ echo '#!\/'
#!\/

History expansion can be disabled in the interactive shell by using set +H, which allows you to use double quotes:

$ set +H
$ echo "#!\/"
#!\/

In general, if you do not require variables to be interpolated (such as in this case), you should use single quotes.

Note that it is not necessary to escape the /, so you can remove the \ from before it if your desired output is #!/:

$ echo '#!/'
#!/
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
2

In an interactive shell ! is subject to history expansion. For example, !! is the last command you typed and !$ is the last argument to that command. To avoid history expansion, escape the ! with a backslash or use single quotes.

echo '#!/'

This isn't necessary in shell scripts, only in interactive shells (unless you purposefully enable set -o history and set -o histexpand in the shell script).

Allow me to make one more update. How do you make the following work?

sh -c 'echo \'#!/bin/bash \' '

There's no way to have a single quote inside single quotes. \' doesn't work. So back to double quotes we go.

sh -c "echo '#\!/bin/bash'"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

Some things are interpreted inside double quotes, including both backslashes and history events introduced by an exclamation mark. Use the more powerful single quotes instead:

echo '#!\/'
Peter Westlake
  • 4,894
  • 1
  • 26
  • 35
0

You need to put the text inside single quotes, so that it won't parse.

$ echo '#!/'
#!/
$ echo '#!\/'
#!\/
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

use single quotes instead of double.

echo '#!/'
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
TrackZero
  • 126
  • 6