Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I often use this directly in a shell to test an outcome for scripting, and it works fine:

$ if [ -d mydirectory ] ; then echo YES ; fi
YES

However, if I want to use the negation using exclamation mark, it fails (well, not really fails, but goes into multiline mode waiting for keyboard input, and I have to escape using Ctrl-C):

$ if [ ! -d makehuman ] ; then echo YES ; if
> 
> ^C
$ if [ \! -d makehuman ] ; then echo YES ; if
> 
> ^C

How can I use the negation exclamation mark directly in a shell?

share|improve this question
2  
I put $? in my PS1 so the prompt always shows the exit status of the last foreground command. This makes testing conditions as easy as running [ -d mydir ] and looking at my current prompt. Another way to test with less typing and w/o using the prompt is [ -d mydir ] && echo yes. – jw013 Aug 6 '11 at 13:09
    
Thanks for the tips @jw013, wasn't aware about $? - cheers! – sdaau Aug 6 '11 at 13:51

At the Bash command line, the exclamation point can be escaped with a backslash, just like all special characters. Don't forget the correct if syntax, though!

$ if [ \! -d mydirectory ]; then echo Yay; else echo Nay; fi
share|improve this answer
    
Thanks for that, @Kerrek SB - good to keep that in mind... Cheers! – sdaau Aug 12 '11 at 5:35
up vote 0 down vote accepted

It was a syntax error, the above commands should finish with fi not if

$ if [ ! -d mydirectoryNO ] ; then echo YES ; fi
YES

Anyway, I also found this nice related link: The classic test command [Bash Hackers Wiki]

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .