Skip to content

Posts tagged ‘conditional’

23
nov

Using conditional expressions to improve your shell scripts

You can use these very simple shell script conditional expressions to improve your home-made scripts, making them more efficient and easy to mantain.

To check if a file exists and it’s executable, use:

#!/bin/bash
FILE=/usr/bin/passwd

if [ -x $FILE ];
then
 echo "File $FILE exists and it is executable"
else
 echo "File $FILE does not exists or it isnt executable"
fi

There are several other options. Here’s the full available conditional expressions:

-e: Returns true value if file exists
-f
: Return true value if file exists and regular file
-r: Return true value if file exists and is readable
-w: Return true value if file exists and is writable
-x: Return true value if file exists and is executable
-d: Return true value if exists and is a directory

Have fun improving your scripts !