File Tests
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 7 of 39.
Before a script reads or writes a path, it can test what is there. Each test goes inside [[ ]] with the path after it:
-e: the path exists.-f: it is a regular file.-d: it is a folder.-s: it exists and is bigger than zero bytes.-r: you have permission to read it.
! in front flips a test, so [[ ! -f $1 ]] is true when $1 is not a regular file.
#!/bin/bash
if [[ ! -f $1 ]]; then
echo "No such file: $1"
exit 1
fi
if [[ -s $1 ]]; then
echo "$1 has content"
else
echo "$1 is empty"
fiWith todo.txt holding a line and log.txt empty, bash count.sh todo.txt prints todo.txt has content and bash count.sh log.txt prints log.txt is empty. A folder is not a regular file, so bash count.sh old prints No such file: old and exits with 1.
Challenge
MediumWrite a script that reports what a path is.
- Open
what.sh. It takes one path as its first argument. - Check the path in this order and print one line:
- it does not exist:
PATH: missing - it is a folder:
PATH: folder - you cannot read it:
PATH: not readable - it is an empty file:
PATH: empty file - anything else:
PATH: file with content
- it does not exist:
- Save the file.
Try it: run bash what.sh notes.txt, then bash what.sh photos. They print:
notes.txt: file with content
photos: folderThen run bash what.sh old.txt, a path that does not exist: it prints old.txt: missing.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground