asked in Software by (8.8k points) edited by
0 like 0 dislike
15 views
How I can to check if a file or directory exists in bash, i.e. in Linux terminal/console? How to check if a file or directory exists in GNU/Linux bash command shell?

bash if file exists

1 Answer

0 like 0 dislike
answered by (8.8k points)

Check if file exist

FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exist"
fi

You can also use the double brackets [[ instead of a single one [:

FILE=/etc/resolv.conf
if [[ -f "$FILE" ]]; then
    echo "$FILE exist"
fi

If-else operator:

FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exist"
else 
    echo "$FILE does not exist"
fi

Inline (one line) solution:

[ -f /etc/resolv.conf ] && echo "$FILE exist"
[[ -f /etc/resolv.conf ]] && echo "$FILE exist"

Check if file does not exist

Similar to many other languages, the check expression can be negated using the ! (exclamation mark) logical not operator:

FILE=/etc/docker
if [ ! -f "$FILE" ]; then
    echo "$FILE does not exist"
fi

Inline (one line) solution:

[ ! -f /etc/docker ] && echo "$FILE does not exist"

Check if multiple files exist

Instead of using complicated nested if else constructs you can use -a (or && with [[) to check if multiple files exist:

FILE=/etc/docker
if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then
    echo "$FILE is a directory"
fi
FILE=/etc/docker
if [ -f /etc/resolv.conf && -f /etc/hosts ]; then
    echo "$FILE is a directory"
fi

Equivalent variants without using the IF statement:

[ -f /etc/resolv.conf -a -f /etc/hosts ] && echo "both files exist"
[[ -f /etc/resolv.conf && -f /etc/hosts ]] && echo "both files exist"

Check if directory exist

The operators -d allows you to test whether a file is a directory or not. For example to check whether the "/etc/docker" directory exist you would use:

FILE=/etc/docker
if [ -d "$FILE" ]; then
    echo "$FILE is a directory"
fi

Inline (one line) solution:

[ -d /etc/docker ] && echo "$FILE is a directory"

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

Related questions

0 like 0 dislike
1 answer 16 views
0 like 0 dislike
1 answer 11 views
0 like 0 dislike
1 answer 31 views
0 like 0 dislike
1 answer 10 views
0 like 0 dislike
1 answer 12 views
0 like 0 dislike
1 answer 17 views
0 like 0 dislike
1 answer 41 views
...