0

Command below in interactive shell produces the error which is explained in other questions:

$ echo "Hello World !"
-bash: !": event not found

Why is the error gone when put in a shell script file and executed?

cat <<EOT > test.sh
#!/bin/sh

VAR=1
echo "Hello World !$VAR"
echo "Hello World !2"
echo "Hello World !3"
EOT

None of below produce the error!

chmod a+x ./test.sh
./test.sh
bash   ./test.sh
sh     ./test.sh
source ./test.sh
pmoubed
  • 3,842
  • 10
  • 37
  • 60
  • https://stackoverflow.com/questions/26443880/bash-event-not-found – stefan_aus_hannover Sep 29 '21 at 15:50
  • I am asking why NO error when same commands are executed from shell script file!? – pmoubed Sep 29 '21 at 15:53
  • 1
    History expansion is off by default in scripts. It's an interactive feature only. – Charles Duffy Sep 29 '21 at 15:55
  • `case $- in *H*) echo "History expansion is on";; *) echo "History expansion is off";; esac` -- you'll see different behavior there as well. And as usual with all `$-` / `set` flags, `set -H` will force it on, and `set +H` will force it off. – Charles Duffy Sep 29 '21 at 15:58
  • `set -H` in a script file does not make any difference - it always print `History expansion is off` and echo works properly – pmoubed Sep 29 '21 at 16:14
  • yes I did that - after the shebang I added `set -H` and still echo did not error out – pmoubed Sep 29 '21 at 16:18
  • 1
    ("Why can't I successfully turn on history expansion in a script?" strikes me as a perfectly on-topic question; if you wrote a question demonstrating that, contrary to the preexisting/linked answers, you can't use `set -H` to reenable history expansion in bash, that would be a useful thing -- I'd also gladly reopen this question if it were edited thusly) – Charles Duffy Sep 29 '21 at 16:25

0 Answers0