Linux and Networking

Linux and Networking

4.13. File comparisons.

One of the advantages that shell script has over other programming languages is that it is integrated with the operating system. Operations with files are something natural for it since working with files is one of the main tasks of shell scripts: dealing with files.

Shell script has a lot of expressions to compare files. Let’s see the most useful:

 

if [ -a $FILE ] is a file

If [ -f $FILE ] is a regular file

If [ -d $FILE ] is a directory

If [ -r $FICHERO ] is a file and has read permission

If [ -w $FICHERO ] is a file and has write permission

If [ -x $FICHERO ] is a file and has execute permission

If [ -s $FICHERO ] is a file and has a size greater than 0

If [ $FILE1 -nt $FILE2 ] file1 is newer than file2

If [ $FILE1 -ot $FILE2 ] file1 is older than file2

 

Solved exercise.

You are asked to create a script file testfich.sh that takes two parameters (filename) as input and checks that both files exist, are regular files, and shows the name of the oldest file.

Let’s see a possible solution to this solved exercise:

 

Suggested exercise.

Create a script that displays the number of regular files and directories in a given directory.

 

The Demeter Project