1

Hi everyone I need to check if a file exist with a shell script. I did some digging and ended up with this syntax but I'm not sure why it isn't working (please bear in mind that you are talking to beginner)

I've found that you can add -e for example to check if it exist but I didn't get where these shortcuts came form or their names

#! /bin/bash
if [ "$#" = "1" ] 
then
    if [ -e $($1) ] && [ -f $($1) ] 
        then echo 'the file exists'
    fi

fi
  • 2
    You need to remove the `$( )` parts. And quote `"$1"`. – melpomene May 29 '19 at 07:55
  • The documentation of the `[` command is at http://man7.org/linux/man-pages/man1/test.1.html. – melpomene May 29 '19 at 07:56
  • If you have a file but don't know if it is a text file and which character encoding must be used to read, you have data loss. If you're into guessing, you can do that with help from tools such as `file`. Note: `file` might answer with one among several possibilities. Also note: the guess is based on the current contents of the file. If the writer updates it later, using a guess based on the previous contents might cause an error or loss of text. And if you update it, you could corrupt it for other readers. – Tom Blodget May 29 '19 at 14:37
  • 2
    Is it me or the question about the file being a text file has just been ignored by everyone ? – Camion Dec 10 '21 at 05:29

3 Answers3

3

In idiomatic Bash:

#!/usr/bin/env bash

if [[ -f "${1-}" ]]
then
    echo 'the file exists'
fi

Please keep in mind that this does not tell you whether the file is a text file. The only "definition" of a text file as opposed to any other file is whether it contains only printable characters, and even that falls short of dealing with UTF BOM characters and non-ASCII character sets. For that you may want to look at the non-authoritative output of file "${1-}", for example:

$ file ~/.bashrc
/home/username/.bashrc: ASCII text

More in the Bash Guide.

l0b0
  • 55,365
  • 30
  • 138
  • 223
1
#!/bin/bash
if [ "$#" == 1 ]; then
    if [[ -e "$1" && -f "$1" ]]; then
        echo 'The file exists';
    fi
fi

You should put every conditional && between [[ ]] symbols otherwise it will be interpreted as execute if success.

sergiotarxz
  • 520
  • 2
  • 14
1
#! /bin/sh

FILE=$1    # get filename from commandline

if [ -f $FILE ]; then
    echo "file $FILE exists"
fi

See the fine manual page of test commands, which are built-in in the different shells: man test; man sh; man bash

You will also find many shell primers which explain this very nicely. Or see bash reference manual: https://www.gnu.org/software/bash/manual/bash.pdf

ennox
  • 206
  • 1
  • 5