Bob
Bob

Reputation: 135

How to check if a files exists in a specific directory in a bash script?

This is what I have been trying and it is unsuccessful. If I wanted to check if a file exists in the ~/.example directory

FILE=$1
if [ -e $FILE ~/.example ]; then
      echo "File exists"
else
      echo "File does not exist"
fi

Upvotes: 12

Views: 37550

Answers (3)

Alec
Alec

Reputation: 246

Late to the party here but a simple solution is to use -f

if [[ ! -f $FILE]]
then
  echo "File does not exist"
fi

A few more examples here if you're curious

Upvotes: 2

Eric Renouf
Eric Renouf

Reputation: 14490

You can use $FILE to concatenate with the directory to make the full path as below.

FILE="$1"
if [ -e ~/.myexample/"$FILE" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi

Upvotes: 16

Jahid
Jahid

Reputation: 22428

This should do:

FILE=$1
if [[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]]; then
      echo "File exists and not a symbolic link"
else
      echo "File does not exist"
fi

It will tell you if $FILE exists in the .example directory ignoring symbolic links.

You can use this one too:

[[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]] && echo "Exists" || echo "Doesn't Exist"

Upvotes: 1

Related Questions