Test if file/directory exists in bash

- 1 min

Currently I’m writing a pipeline, better call it a pipeline manager, in BASH. The first part of the script is to create the set up file system so it requests to check if certain files and folders exists.

Hence the idea is to use the BASH tests, that can be performed both using the keyword test and [. The syntax is:

[ parameter FILE ]

or

test parameter FILE

Where parameter can be any one of the following:

An example to test if a file exists in a script file could be:

#!/bin/bash
FILE=$1

if [ -f $FILE ]; then
   echo "File $FILE exists"
else
   echo "File $FILE does not exists"
fi

The same used as an in-line command:

$ [ -f ~/blog/bash_test.md ] && echo "File exists" || echo "File does not exists"
comments powered by Disqus
rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora