I realize that !
has special significance on the commandline in the context of the commandline history, but aside from that, in a runing script the exclamation mark can sometimes cause a parsing error.
I think it has something to do with an event
, but I have no idea what an event is or what it does. Even so, the same command can behave differently in different situations.
The last example, below, causes an error; but why, when the same code worked outside of the command substitution? .. using GNU bash 4.1.5
# This works, with or without a space between ! and p
{ echo -e "foo\nbar" | sed -nre '/foo/! p'
echo -e "foo\nbar" | sed -nre '/foo/!p'; }
# bar
# bar
# This works, works when there is a space between ! and p
var="$(echo -e "foo\nbar" | sed -nre '/foo/! p')"; echo "$var"
# bar
# This causes an ERROR, with NO space between ! and p
var="$(echo -e "foo\nbar" | sed -nre '/foo/!p')"; echo "$var"
# bash: !p': event not found
protected
would have been more appropriate. (protected by 'single quotes')var=$(…)
(no double quotes), and it will work like (I think) you expect. This is still “safe” because the value part of a simple assignment is not subject to word splitting or globbing (though this may not be true of assignments done through builtins (e.g.export
,local
, etc.) under all shells). Unfortunately, this does not extend beyond simple assignments since the double quotes are the way to protect against word splitting and globbing while still getting other types of expansion in other contexts.