Linux – Single command to check if file exists, and print (custom) message to stdout

fileslinux

Hope it's OK to note this, now that I've encountered it:

I'm already aware that one can test for file existence using the test ([) command:

$ touch exists.file
$ if [ -f exists.file ] ; then echo "yes" ; else echo "no" ; fi
yes
$ if [ -f noexists.file ] ; then echo "yes" ; else echo "no" ; fi
no

… but that's a bit of typing there :) So, I was wandering if there is a "default" single command, that will return the file existence result to stdout?

I can also use test with the exit status $?:

$ test -f exists.file ; echo $?
0
$ test -f noexists.file ; echo $?
1

… but this is still two commands – and the logic is also "inverse" (0 for success, and nonzero for failure).

The reason I'm asking is that I need to test for file existence in gnuplot, whose "system("command") returns the resulting character
stream from stdout as a string.
"; in gnuplot I can do directly:

gnuplot> if (0) { print "yes" } else { print "no" }
no
gnuplot> if (1) { print "yes" } else { print "no" }
yes

so I'd basically like to be able to write something like this (pseudo):

gnuplot> file_exists = system("check_file --stdout exists.file")
gnuplot> if (file_exists)  { print "yes" } else { print "no" }
yes

… unfortunately, I cannot use that directly via test and $?:

gnuplot> file_exists = system("test -f exists.file; echo $?")
gnuplot> if (file_exists)  { print "yes" } else { print "no" }
no

… I'd have to invert the logic.

So, I'd basically have to come up with sort of a custom script solution (or writing a script inline as one-liner) … and I thought, if there is already a default command that can print 0 or 1 (or a custom message) to stdout for file existence, then I don't have to do so :)

(note that ls may be a candidate, but it's stdout output is far too verbose; and if I want to avoid that, I'd have to suppress all output and again return exist status, as in

$ ls exists.file 1>/dev/null 2>/dev/null ; echo $? 
0
$ ls noexists.file 1>/dev/null 2>/dev/null ; echo $? 
2

… but that's again two commands (and more typing), and "inverted" logic…)

So, is there a single default command that can do this in Linux?

Best Answer

Sounds like you need the exit status reversed, so you could do:

system("[ ! -e file ]; echo $?")

or:

system("[ -e file ]; echo $((!$?))")

(note that -f is for if file exists and is a regular file).

Related Question