Bash shell - Check if value is valid directory.

  1. The problem statement, all variables and given/known data:

The script usage will be as follows:
library.third source_directory [destination directory]

  • Your script will display an appropriate error message and exit with status 3 if no parameters are given
  • Your script will display an appropriate error message and exit with status 4 if the source directory does not exist
  • Your script will display an appropriate error message and exit with status 5 if the source is not a directory
  • Your script will display an appropriate error message and exit with status 6 if destination directory does not exist
  • Your script will display an appropriate error message and exit with status 7 if destination is not a directory
  1. Relevant commands, code, scripts, algorithms:

Simple Unix Bash commands have been used in this program, that is all that has been taught in the course so far. By this, I mean if statements and basic looping, nothing complex.

  1. The attempts at a solution (include all code and scripts):

The section I am having trouble with is:
Your script will display an appropriate error message and exit with status 5 if the source is not a directory.

The statement does not recognize any file type as a directory.

DIR="$1"

if [ $# -lt 1 ]
then
        echo "Incorrect Usage"
        exit 3

elif [ ! -d "$DIR" ]
then
        echo "Directory does not exist!"
        exit 4

elif [ "$DIR" != -d ]
then
        echo "Not a Directory"
        exit 5
else
        echo "Path is okay"

fi
  1. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):

Seneca College of Applied Arts of Technology, Toronto, Canada, Michal Heidenreich, OPS105

you almost got it:

....
elif [ ! -e "$DIR" ] 
then         
   echo "Directory does not exist!"         
   exit 4  
elif [ ! -d "$DIR" ] 
then         
    echo "Not a Directory"        
    exit 5
....
1 Like

You're almost there.

elif [ "$DIR" != -d ]

This checks if the string "$DIR" is the same as the string "-d", which of course it isn't.

You had it right in the last statement, with [ ! -d "$DIR" ] . That causes an error if "$DIR" isn't a dir or it doesn't exist.

So you really have it covered with the first two. Just chop out all of this:

elif [ "$DIR" != -d ]
then
        echo "Not a Directory"
        exit 5

and you'll be okay.

---------- Post updated at 04:11 PM ---------- Previous update was at 04:10 PM ----------

Oh, and if they insist you check if it exists or not seperately, check with [ ! -e "$DIR" ] before you check with -d.

1 Like