Home shell-script Q&A
Post
Cancel

shell-script Q&A

Test

1
2
3
test EXPRESSION
[ EXPRESSION ]
[[ EXPRESSION ]]

If you want your script to be portable, you should prefer using the old test [ command, which is available on all POSIX shells. The new upgraded version of the test command [[ (double brackets) is supported on most modern systems using Bash, Zsh, and Ksh as a default shell.

Check if file exists

1
2
3
4
5
6
7
8
9
10
11
12
13
14
FILE=/etc/resolv.conf
if test -f "$FILE"; then
    echo "$FILE exists."
fi

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

FILE=/etc/resolv.conf
if [[ -f "$FILE" ]]; then
    echo "$FILE exists."
fi
1
2
3
test -f /etc/resolv.conf && echo "$FILE exists."
[ -f /etc/resolv.conf ] && echo "$FILE exists."
[[ -f /etc/resolv.conf ]] && echo "$FILE exists."

check if file does not exist

1
2
3
4
FILE=/etc/docker
if [ ! -f "$FILE" ]; then
    echo "$FILE does not exist."
fi
1
[ ! -f /etc/docker ] && echo "$FILE does not exist."

check if directory exist

1
2
3
4
FILE=/etc/docker
if [ -d "$FILE" ]; then
    echo "$FILE is a directory."
fi
1
[ -d /etc/docker ] && echo "$FILE is a directory."

check if multiple file exists

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

1
2
3
if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then
    echo "Both files exist."
fi
1
2
3
if [[ -f /etc/resolv.conf && -f /etc/hosts ]]; then
    echo "Both files exist."
fi
1
[ -f /etc/resolv.conf -a -f /etc/hosts ] && echo "Both files exist."
1
[[ -f /etc/resolv.conf && -f /etc/hosts ]] && echo "Both files exist."

file test operators

This post is licensed under CC BY 4.0 by the author.