Exercise: Test Multiple Aspects

by mike on November 26, 2011

Test Multiple Aspects
In many situations you will want to test for multiples aspects of the file or directory.    There are also a number of ways that you can set up these multiple tests.  This example looks for a file that exists and is writable.

if [ -f $file  ] && [ -w $file ]
echo $file exists and is writable
echo  $file exists but it is not writable

Create a script that tests for the existence of a file and determines if it is writeable.

As a regular user create a test directory and then create an empty file called log.  Notice this command does it all on one line separating commands with a semi-colon.
cd;mkdir test;cd test;touch log

Use the test builtin to verify how the script will work.  This is a simple process in starting to build a script.  The “-w” option is to see if the file is writeable and the “-f” option is to see if the file is a file (as opposed to a directory,link etc.).  The “echo $?” is showing the success of failure of the command.  So if the command is executed and you see “0″ that is success, any other number is failure.

[ -w log ];echo $?
[ -f log ];echo $?

You could have also done this:

test -w log;echo $?
test -f log;echo $?

Now you have the basics working from the command line, build it into a script.  The variable “chkfile” can be used to list any file you want down the road.    The test checks to see if the file is a file and if that command produces a “0″ (success) it executes the second command which checks to see if the file is writeable.  The if…then..else allows you to choose the output of your command.

if [ -f $chkfile ] && [ -w $chkfile ]
echo $chkfile exists and it is writeable
echo $chkfile exists but is not writeable

Make the script executable.

chmod 755 test.sh

Execute teh script.

{ 1 comment }

Geoff November 28, 2011 at 9:09 am

When you say “the “-f” option is to see if the file is a file (as opposed to a directory,link etc.)”, presumably by “link” you mean symbolic link, but test -f follows symbolic links. To test that $file is a plain file and not a symbolic link you need:

[ -f "$file" ] && [ ! -L "$file" ]

(Also note the quoting: always double-quote variable expansions unless you specifically want field splitting and pathname expansion done.)

Comments on this entry are closed.

Previous post:

Next post: