TOPIC: DIRNAME
Detecting file ownership in Korn shell scripts
17th October 2007I recently was having a play with using a shell script to do some folder creation to help me set up a system for testing, and I started to hit ownership issues that caused some shell script errors. At the time, I didn't realise that there is a test that you can perform for ownership. The "-o" in the code below kicks in the test condition and avoids the error in question.
if [[ -o $dirname ]]
then
cd test
for i in 1 2 3 4 5 6 7 8 9 10
do
if [[ -d study$i ]]
then
:
else
mkdir study$i
fi
done
ls
cd ~
fi
Previously, I shared a way to test for directory (-d operator) and file (-f operator) existence that follows the above coding convention. However, there are a plethora of others and I have made a list of them here:
Operator | Condition |
-e file |
File exists |
-L file |
File is a symbolic link |
-r file |
User has read access to file |
-s file |
File is non-empty |
-w file |
User has write access to file |
-x file |
User has execute-access to file |
-G file |
User's effective group ID is the same as that of the file |
file1 -nt file2 |
File 1 is newer than file2 |
file1 -ot file2 |
File 1 is older than file2 |
file1 -et file2 |
File 1 was created at the same time as file2 |
It's all useful stuff when you want to rid the command line output of errors in an above board way. These are the kinds of things that often make life easier...
Negative logic in Korn shell scripts
16th October 2007I was looking for a way to negative logic, doing something when a condition is not satisfied, that is, and found that the way to do it is to do nothing when the condition is satisfied and something when it isn't. Being used to saying do something when a condition is false, this does come as a surprise. In time, I may find another way on my UNIX shell scripting journey. Meanwhile, the code below will only create a directory when it doesn't already exist.
dirname=test
if [[ -d $dirname ]]
then
: # the colon operator means do nothing
else
mkdir test
fi