Checking the existence of a file

Need a bash script that takes 1 parameter, i.e. I call it

./script filename

And it checks if the file exists and outputs a message that the file either exists or not, you can name it exists.sh.

 2
Author: mymedia, 2012-08-29

4 answers

I'll pay my 5 kopecks.

Instead of [, you can use the test command:

if test -f "$FILE"; then  echo yes; fi
test -f "$FILE" && echo yes

, etc.

If you look at the *nix commands more closely, you will find:

avp@avp-xub11:~/src/ig/web-agent$ which [
/usr/bin/[
avp@avp-xub11:~/src/ig/web-agent$ which ] || echo no ']' in `uname`
no ] in Linux
avp@avp-xub11:~/src/ig/web-agent$`

That [ is a command (utility), and ] is just a decoration (when skipping which /bin/bash and /bin/sh swear, but work).

avp@avp-xub11:~/src/ig/web-agent$ [ -f xaxa || echo no in ./
bash: [: пропущен ']'
no in ./
avp@avp-xub11:~/src/ig/web-agent$ sh
$ [ -f xaxa || echo no in ./
sh: 1: [: missing ]
no in ./
$
 10
Author: avp, 2017-06-13 04:47:44

The check is carried out with the help of the operator ! and the expressions-f

#!/bin/bash
FILE=$1

if [ ! -f "$FILE" ]; then
    echo "Файл $FILE не существует"
fi

Read more here: Introduction to if.

 6
Author: ыук, 2017-06-13 04:45:17
[ -f "$1" ] && echo "Существует" && exit 0
echo "Не суущесствует" && exit 1
 6
Author: zigzag, 2017-06-13 04:45:37

To solve such problems, it is sometimes convenient to use one-liners in perl:

# perl -e 'if ($ARGV[0] && -e $ARGV[0]){print "Exists\n";} else {print "No\n";};' /i/1.txt

Exists

# perl -e 'if ($ARGV[0] && -e $ARGV[0]){print "Exists\n";} else {print "No\n";};' /i/2.txt

No

 4
Author: Ilya Makarov, 2012-08-31 11:50:41