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.

#!/bin/bash
file=/etc/yum.repos.d/rpmforge.repo
if [ -f $file  ] && [ -w $file ]
then
echo $file exists and is writable
else
echo  $file exists but it is not writable
fi

Exercise:
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 $?
0
[ -f log ];echo $?
0

You could have also done this:

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

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.

#!/bin/bash
chkfile=log
if [ -f $chkfile ] && [ -w $chkfile ]
then
echo $chkfile exists and it is writeable
else
echo $chkfile exists but is not writeable
fi

Make the script executable.

chmod 755 test.sh

Execute teh script.
./test.sh

{ 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: