12

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
2
  • Write the path you want to check in the test. Do you want to check for a $FILE ~/.example file? Commented Apr 28, 2015 at 18:19
  • How we can check *.txt files available in /home/tmp directory ?? Commented May 11, 2022 at 20:52

3 Answers 3

16

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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"

2 Comments

This specifically tests whether it's a plain file. The -e in the OP's question tests for anything with the right name, e.g. it could be a directory.
Thanks for clarification, @Kenster, I took file as plain file, even though OP used -e. Maybe he is meaning both file and folder by file in the context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.