Checking File Types and Permissions
The previous lesson asked whether a path exists. A script often needs to know more: is this a regular file or a directory, can the current user read it, can the script write to it, can it be run as a program? Bash answers these questions with a second group of file test operators. Using them before acting lets a script print a clear message, choose a different action, or stop early, instead of failing halfway through with an error from some other command.
Understanding the Concept
Every file on a Linux system has a type and a set of permissions.
- The type says what kind of object the path is: a regular file, a directory, a symbolic link, a device, a named pipe, or a socket.
- The permissions say who may read, write, or execute it. Three groups of people are distinguished: the owner, the group, and everyone else. Each group can be given read (
r), write (w) and execute (x) rights.
You can see both with ls -l or stat:
stat -c '%A %U %n' file.txt run.sh dir link.txt
Output:
-rw-r--r-- nobody file.txt
-rwxr-xr-x nobody run.sh
drwxr-xr-x nobody dir
lrwxrwxrwx nobody link.txt
The first character of the mode string is the type: - for a regular file, d for a directory, l for a symbolic link. The next nine characters are the three groups of rwx rights. File test operators let a script ask the same questions that you answer by reading this listing, and they do it for the user who is running the script.
The -c '%A %U %n' option is specific to GNU stat. On macOS, stat uses different options, so treat this command as an inspection tool for Linux rather than something a portable script depends on.
How It Works
A permission test does not read the mode string and apply the rules itself. It asks the operating system whether the current process would be allowed to perform the operation. That makes the answer depend on who is running the script. A file with mode 600 owned by another user is unreadable for you and readable for its owner, so [ -r file ] can give different answers when two people run the same script.
All the operators follow the pattern from lesson 68: a unary operator followed by a path, placed inside [ ] or [[ ]], producing exit status 0 for true and a non-zero status for false. When the path does not exist, every one of these tests is false.
Testing File Types
These operators check the kind of object at a path:
| Operator | True when the path is |
|---|---|
-f path | a regular file |
-d path | a directory |
-L path or -h path | a symbolic link (the link itself, even if it is broken) |
-p path | a named pipe (FIFO) |
-S path | a socket |
-b path | a block device, such as a disk |
-c path | a character device, such as a terminal or /dev/null |
Here they are applied to a few objects created for the example:
mkdir dir
printf 'data\n' > file.txt
ln -s file.txt link.txt
mkfifo pipe1
[ -f file.txt ]; echo "-f file: $?"
[ -d dir ]; echo "-d dir: $?"
[ -L link.txt ]; echo "-L link: $?"
[ -p pipe1 ]; echo "-p pipe1: $?"
[ -c /dev/null ]; echo "-c /dev/null: $?"
[ -b /dev/null ]; echo "-b /dev/null: $?"
Output:
-f file: 0
-d dir: 0
-L link: 0
-p pipe1: 0
-c /dev/null: 0
-b /dev/null: 1
Every test matches one kind of object, and the device /dev/null is a character device, so -c is true and -b is false. Block devices, character devices and sockets are rare in everyday scripts. The two you will use constantly are -f and -d.
Note that -f and -d follow symbolic links. A link that points to a regular file passes -f, as lesson 71 showed. Only -L and -h look at the link itself.
Testing Permissions
Three operators check the rights of the user running the script:
| Operator | True when the current user can |
|---|---|
-r path | read the path |
-w path | write to the path |
-x path | execute the path (for a directory: enter it) |
The meaning of x on a directory is easy to miss. To cd into a directory, or to open a file inside it by name, you need x on the directory. Having only r lets you list the names but not use them.
Here is a set of files with different modes, tested by an ordinary user (not the administrator):
chmod 644 file.txt # rw-r--r--
chmod 755 run.sh # rwxr-xr-x
chmod 000 locked.txt # ----------
chmod 444 readonly.txt # r--r--r--
[ -r file.txt ]; echo "-r file.txt: $?"
[ -w file.txt ]; echo "-w file.txt: $?"
[ -x file.txt ]; echo "-x file.txt: $?"
[ -x run.sh ]; echo "-x run.sh: $?"
[ -r locked.txt ]; echo "-r locked.txt: $?"
[ -w readonly.txt ]; echo "-w readonly.txt: $?"
[ -r readonly.txt ]; echo "-r readonly.txt: $?"
Output:
-r file.txt: 0
-w file.txt: 0
-x file.txt: 1
-x run.sh: 0
-r locked.txt: 1
-w readonly.txt: 1
-r readonly.txt: 0
Reading the results against the modes explains each line. The owner of file.txt has rw-, so reading and writing pass and executing fails. run.sh has x set, so -x passes. locked.txt has no rights at all, so even its owner cannot read it. readonly.txt can be read but not written.
Permission Tests Follow the User
The administrator account, root, is treated differently. Running the same checks as root gave:
root -r locked (000): 0
root -w readonly (444): 0
root -x noexec (644): 1
root -x locked (000): 1
The administrator can read and write files regardless of their mode, so -r and -w are true even for mode 000. Executing is different: -x on a regular file is true only when at least one execute bit is set, even for root. A script that tests permissions while running as root, for example inside a container, therefore cannot use -r and -w to discover whether a file's mode is restrictive. Lesson 68 made the same point about the administrator account and these two operators.
Checking Directories
For a directory, the three operators answer three separate questions:
[ -w dir ]; echo "can create files in dir: $?"
[ -x dir ]; echo "can enter dir: $?"
Output:
can create files in dir: 0
can enter dir: 0
To place a new file in a directory, a user needs both w and x on that directory. A script that must write a log file there should test both:
logdir=/var/log/myapp
if [ -d "$logdir" ] && [ -w "$logdir" ] && [ -x "$logdir" ]; then
echo "log directory is usable"
else
echo "cannot write to $logdir" >&2
fi
The directory named closed in the experiment had mode 600 (rw- for the owner and nothing else). It shows how the answers can split:
[ -r closed ]; echo "-r closed: $?"
[ -x closed ]; echo "-x closed: $?"
Output:
-r closed: 0
-x closed: 1
The owner may list the names in the directory but may not enter it or open anything inside.
Checking Who Owns a File
Two operators compare a file with the current user:
| Operator | True when |
|---|---|
-O path | the path is owned by the current effective user |
-G path | the path's group matches the current effective group |
[ -O file.txt ]; echo "-O file.txt: $?"
[ -O /etc/hostname ]; echo "-O /etc/hostname: $?"
Output:
-O file.txt: 0
-O /etc/hostname: 1
The file created by the user is owned by that user, and the system file is owned by root, so the second test fails for an ordinary user. A script can use -O before a command such as chmod that only the owner may run.
Special Permission Bits
Three operators check the special bits that appear in the mode string as s or t:
| Operator | True when the path has |
|---|---|
-u path | the setuid bit: the program runs with its owner's rights |
-g path | the setgid bit |
-k path | the sticky bit |
[ -u /usr/bin/passwd ]; echo "setuid passwd: $?"
[ -k /tmp ]; echo "sticky /tmp: $?"
Output:
setuid passwd: 0
sticky /tmp: 0
On the test machine, ls -ld showed -rwsr-xr-x for /usr/bin/passwd (the s is the setuid bit) and drwxrwxrwt for /tmp (the final t is the sticky bit, which lets users delete only their own files there). These tests are used mostly in security audits, a topic that returns in lessons 154 to 161.
Checking Whether Input or Output Is a Terminal
The -t operator takes a file descriptor number instead of a path. It is true when that descriptor is connected to a terminal:
[ -t 0 ]; echo "stdin is a terminal: $?"
[ -t 1 ]; echo "stdout is a terminal: $?"
Typed into an interactive terminal, both lines print 0. When the same commands run with their input or output redirected, the result is 1. In the test environment, output was captured, so both printed 1:
stdin is a terminal: 1
stdout is a terminal: 1
This is how a script decides whether to ask questions or print colors. If standard output goes to a file or another command, color codes would only clutter the result, so scripts often print them only when [ -t 1 ] is true. Standard input and output were the subject of lesson 56.
Choosing Between Tests Before Running a File
Before running a script, you can tell the user precisely what is wrong:
for s in run.sh noexec.sh missing.sh; do
if [ -x "$s" ]; then
echo "$s: executable"
elif [ -e "$s" ]; then
echo "$s: exists but not executable"
else
echo "$s: not found"
fi
done
Output:
run.sh: executable
noexec.sh: exists but not executable
missing.sh: not found
The if ... elif ... else chain works through the questions from most specific to least specific: it first asks whether the file can be run, then whether it exists at all, and finally concludes that it is missing. Without these checks, running ./noexec.sh produces only a terse error and exit status 126:
bash: ./noexec.sh: Permission denied
A related check is whether a command is available, which is a question about the PATH rather than a file. The command -v builtin prints the path of a command and returns status 0 when it exists:
command -v bash
command -v nosuchtool; echo "status: $?"
Output:
/usr/bin/bash
status: 1
The printed path for bash depends on the system. Combining command -v with -x confirms that the program is both found and runnable:
[ -x "$(command -v bash)" ]; echo "bash found and executable: $?"
Output:
bash found and executable: 0
Combining Tests with Bash Conditionals
Several conditions can be joined inside one [[ ]]:
[[ -f file.txt && -r file.txt ]]; echo "readable regular file: $?"
[[ -d dir && -w dir && -x dir ]]; echo "usable directory: $?"
Output:
readable regular file: 0
usable directory: 0
With [ ], write the tests separately and join them with && or ||. The operators -a and -o also exist inside [ ], but they can be ambiguous. Lesson 74 covers logical operators in detail.
One more detail that causes confusion: -a also has an old meaning as a unary file test, equal to -e. Both [ -a file.txt ] and [[ -a file.txt ]] were true for an existing file. Dash rejects the unary form (sh: 1: [: -a: unexpected operator). Use -e in new scripts, because -a has two meanings, is easy to misread, and is not portable.
Practical Applications
A script that processes a log file only after confirming it is a readable regular file, and gives a specific message for each problem:
#!/usr/bin/env bash
log="$1"
if [ ! -e "$log" ]; then
echo "error: $log does not exist" >&2
exit 1
elif [ ! -f "$log" ]; then
echo "error: $log is not a regular file" >&2
exit 1
elif [ ! -r "$log" ]; then
echo "error: $log is not readable by $(id -un)" >&2
exit 1
fi
grep -c ERROR "$log"
Each branch handles one reason the file cannot be used. Printing the user name with $(id -un) makes the permission message easier to understand when the script runs under a different account. The exit 1 lines end the script with a failure status, which lesson 118 explains, and the >&2 redirections send the messages to standard error.
A script that decides at startup whether it may use colors:
if [ -t 1 ]; then
green=$'\033[32m'
reset=$'\033[0m'
else
green=""
reset=""
fi
echo "${green}done${reset}"
When run in a terminal, the word done appears in green. When the output is piped or redirected, the variables are empty and only the plain word is printed. The $'...' form for escape characters comes from lesson 47.
Portability
Under Dash, the shell behind sh on Debian and Ubuntu, the operators -O, -G, -k, -u and -p all worked inside [ ] in the test, and so did the ones from lesson 71. The one exception is the unary -a, which Dash rejects. The [[ ]] form does not exist in Dash at all (lesson 71). The tests -e, -f, -d, -r, -w, -x, -s and -L are the safest choice for scripts that must run on any system, because they are the ones the POSIX standard describes most widely. Other shells and older systems may support fewer operators than the Dash version tested here. Always quote every variable.