The test command ([
here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:
if [ ! -f /tmp/foo.txt ]; then echo "File not found!" fi
ID : 116
viewed : 93
Tags : bashfile-ioscriptingbash
96
The test command ([
here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:
if [ ! -f /tmp/foo.txt ]; then echo "File not found!" fi
80
Bash File Testing
-b filename
- Block special file
-c filename
- Special character file
-d directoryname
- Check for directory Existence
-e filename
- Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename
- Check for regular file existence not a directory
-G filename
- Check if file exists and is owned by effective group ID
-G filename set-group-id
- True if file exists and is set-group-id
-k filename
- Sticky bit
-L filename
- Symbolic link
-O filename
- True if file exists and is owned by the effective user id
-r filename
- Check if file is a readable
-S filename
- Check if file is socket
-s filename
- Check if file is nonzero size
-u filename
- Check if file set-user-id bit is set
-w filename
- Check if file is writable
-x filename
- Check if file is executable
How to use:
#!/bin/bash file=./file if [ -e "$file" ]; then echo "File exists" else echo "File does not exist" fi
A test expression can be negated by using the !
operator
#!/bin/bash file=./file if [ ! -e "$file" ]; then echo "File does not exist" else echo "File exists" fi
76
You can negate an expression with "!":
#!/bin/bash FILE=$1 if [ ! -f "$FILE" ] then echo "File $FILE does not exist" fi
The relevant man page is man test
or, equivalently, man [
-- or help test
or help [
for the built-in bash command.
68
[[ -f $FILE ]] || printf '%s does not exist!\n' "$FILE"
Also, it's possible that the file is a broken symbolic link, or a non-regular file, like e.g. a socket, device or fifo. For example, to add a check for broken symlinks:
if [[ ! -f $FILE ]]; then if [[ -L $FILE ]]; then printf '%s is a broken symlink!\n' "$FILE" else printf '%s does not exist!\n' "$FILE" fi fi
58
It's worth mentioning that if you need to execute a single command you can abbreviate
if [ ! -f "$file" ]; then echo "$file" fi
to
test -f "$file" || echo "$file"
or
[ -f "$file" ] || echo "$file"