2

echo "!omg" outputs -bash: !omg: event not found

  1. How I can output !omg string to console?
  2. My problem arises because I need to execute some node code using command line:

    node -e "var code = function(){ console.log('which contains a lot of !'); }; !func();"

user606521
  • 14,486
  • 30
  • 113
  • 204

3 Answers3

3

Use single quotes:

echo '!omg'

If you have quotes in your input, e.g. to print console.log('lalala'), say:

echo $'console.log(\'lalala\')'

Alternatively, say:

cat | command << EOF
my_string_with_crazy_characters
EOF

The last form wouldn't require you to escape any character in the input.

devnull
  • 118,548
  • 33
  • 236
  • 227
  • It works but it also strips any `'` in the string so `echo 'console.log('lalala')'` prints `console.log(lalala)` instead of `console.log('lalala')` - is there any workaround for this? I have to pass javascript code so many different characters may appear in source... And I cant load script from file. – user606521 Dec 13 '13 at 13:00
  • @user606521 See edit above. – devnull Dec 13 '13 at 13:03
  • You could also prefer printf to echo (it's more portable!) : `printf '%s\n' "$something"` will print the content of $something variable. – Olivier Dulac Dec 13 '13 at 13:13
  • 1
    @OlivierDulac It's a chicken and egg problem. The problem is essentially about getting quotes and crazy characters as is. In that event, the `cat` solution would be ideal as it obviates the need of escaping the input. – devnull Dec 13 '13 at 13:17
1

You could turn off history expansion as follows

[username@hostname ~]$ set +o histexpand
[username@hostname ~]$ echo hello!world!anything
hello!world!anything

to turn on

[username@hostname ~]$ set -o histexpand
[username@hostname ~]$ echo hello!world!anything
-bash: !world!anything: event not found
Jason Heo
  • 9,956
  • 2
  • 36
  • 64
1

I prefer to unset the shell variable histchars to effectively disable history expansion:

$ echo !omg
bash: !omg: event not found
$ histchars=
$ echo !omg
!omg
Alfe
  • 56,346
  • 20
  • 107
  • 159