NASutils Knowledge BaseUnofficialPolski

Bash · lesson 7 of 30 · Decisions and loopsTest files and text

-f, -d, -e and -s ask about files, == compares text with a pattern.

Programming on the NAS › Bash in 30 lessons

07-tests.sh Download 07-tests.sh

#!/usr/app/TurboShell/bin/bash
day=Sunday
free=12
[[ -f words.txt ]] && echo "words.txt is a file"
[[ -d photos ]] && echo "photos is a folder"
[[ -e missing.txt ]] || echo "there is no missing.txt"
[[ -s words.txt ]] && echo "words.txt is not empty"
[[ $day == S* ]] && echo "$day starts with S"
[[ -z ${comment:-} ]] && echo "comment is empty"
((free < 20)) && echo "low space"
if [[ $day == Sunday && -d photos ]]; then
  echo "both are true"
fi

Terminal

$ bash 07-tests.sh
words.txt is a file
photos is a folder
there is no missing.txt
words.txt is not empty
Sunday starts with S
comment is empty
low space
both are true

Exercise

Test whether a file is newer than another one with -nt.