Event not found csh

csh
Programmer picture Programmer · Oct 4, 2013 · Viewed 11.4k times · Source

I have this very simple csh script.

#!/bin/csh
        echo "Hello World!"
        echo "How are you today?"

But I am getting the error ": Event not found.

What is wrong?

Answer

Keith Thompson picture Keith Thompson · Oct 4, 2013

csh uses the ! character for history substitution. So in the sequence !", the " is not treated as the closing quotation mark for the string; rather, the shell searches for something in your command history starting with ", just as typing !foo at the command line repeats the most recent command starting with foo.

At least for the original csh, this substitution is always done, even in single-quoted strings (so changing double quotes to single quotes won't necessarily help).

The only way to escape a ! character is with a \ backslash:

#!/bin/csh -f
echo "Hello World\!"
echo "How are you today?"

(On some systems, I find that using single quotes rather than double quotes does avoid the error. I think that's because on those systems /bin/csh is a symlink to /bin/tcsh, which works a bit differently. You shouldn't depend on that if you want your script to be portable.)

Note that I've also added a -f option to the #! line. This prevents the shell from executing your $HOME/.cshrc on startup, and it's generally a good idea for csh scripts. It makes them run a bit faster, and it prevents accidental dependence on your own .cshrc, which could be a problem when others run your script.

And in any question about csh scripting, I am legally obligated [*] to post this link:

http://www.perl.com/doc/FMTEYEWTK/versus/csh.whynot

[*] I am not actually legally obligated to post this link.