1.

How would you check if a directory exists in a shell script under Unix/Linux Operating Systems?

Answer»

The test command evaluates conditional expressions. Upon evaluating the expression parameter, the test command returns 0 (TRUE) if the expression is True, otherwise, it returns a nonzero (False) exit value. A nonzero exit value is also returned if no parameters are specified. You can use the test command with the -d option to find out WHETHER a DIRECTORY exists.

Example: If you wanted to verify the existence of the directory which is stored in a variable $mydir, you could use the FOLLOWING command expression:mydir= "home/etc/Datafiles/"if [ -d "$mydir" ] then echo "$mydir exists." else echo "Error: $mydir does not exist."fi

For directories with white/black spaces in their names, always ENCLOSE the variable "$mydir" in double-quotes. For example:

mydir= "home/etc/Data Files/"if [ -d "$mydir" ] then echo " '$mydir' exists." else echo "Error: '$mydir' does not exist."fi


Discussion

No Comment Found