How to check if a files exists in a specific directory in a bash script?
26,000
Solution 1
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
Solution 2
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"
Solution 3
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
Author by
Bob
Updated on March 14, 2020Comments
-
Bob over 4 years
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
-
Etan Reisner about 9 yearsWrite the path you want to check in the test. Do you want to check for a
$FILE ~/.example
file? -
Bhagesh Arora about 2 yearsHow we can check *.txt files available in /home/tmp directory ??
-
-
yaKashif about 9 yearsThis 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. -
Jahid about 9 yearsThanks 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.