If option -a does not seem to work for me in negative form

Hi All, In the past, in bash, I have used the -e and -f options for checking if a file exists, adding ! to create not exists. In the LA course the -a option is used, which works until I use the !, then it fails.  The -e and -f options work fine with or without the !.

The below code works in Terry's video, so it makes me think there is something different about my Linux envirnment. Any ideas?

For example:

[root@CentOS bin]# cat testfile.sh

#!/bin/bash

# test for existence of indicated file name

FILENAME=$1

echo "Testing for the existence of and file called $FILENAME"

if [ ! -a $FILENAME ]

then

echo "The file $FILENAME does NOT exist."

fi

[root@CentOS bin]# ll

total 2

-rwxr-xr-x. 1 root root 251 Oct 3 13:43 simpleif.sh

-rwxr-xr-x. 1 root root 213 Oct 3 15:49 testfile.sh

[root@CentOS bin]# testfile.sh simpleif.sh

Testing for the existence of and file called simpleif.sh

The file simpleif.sh does NOT exist.

[root@CentOS bin]# testfile.sh askaslkas

Testing for the existence of and file called askaslkas

The file askaslkas does NOT exist.




  • post-author-pic
    Michael M
    10-03-2018

    Hello, 


    I am sorry that you are having an issue. I am not sure what the difference would be, but could you try to move the ! outside of the bracket.
     
    ...

    if

          !   [ -a $FILENAME ]

    then

    ...


    Make sure that you have your spacing correct between the ! and the bracket. I am not sure what Distro you are using, but you may try this and see if it solves the issue for you. 

  • post-author-pic
    David M
    10-03-2018

    Thanks  @secondthief , it’s CentOS 7 and I did make sure the spacing was correct so that wouldn’t be it. It’s very odd. I will move the ! out to the left and see what happens. I have a dev registered version of Rhel 7.5 running as a guess. Will try it there too.

  • post-author-pic
    David M
    10-03-2018

    Same behavior in rhel 7.5. It works fine without the !, but with the ! the script thinks files that exist don't exist.

    Moving it out tot he left DID work. Strange how it worked for Terry in the brackets.

Looking For Team Training?

Learn More