check if a file or folder exists

Test in a script whether a path exists, is a file, a folder, empty or runnable.

  • shell
  • development

Steps

  1. [ -f config.txt ] && echo 'it is a file'

    a regular file

  2. [ -d logs ] || mkdir logs

    a folder; make it when it is missing

  3. [ ! -e path ] && echo 'nothing there'

    nothing at all by that name

  4. [ -s data.csv ] && echo 'not empty'

    a file that is not empty

  5. [ -x script.sh ] && ./script.sh

    a file you may run

  6. [ -L link ] && echo 'a symbolic link'

    a link

Notes

  • Quote paths that may have spaces: [ -f "$file" ].
  • In scripts, if [ -d "$dir" ]; then … fi does the same over several lines.

Commands used

  • test

Each has a page in lore: lore test opens it.