What would be the best means of being able to check whether a specified path (./filename followed by the filepath) is a directory? Ideally I would also be looking to print the list of the files within the directory should they be present. Thanks.
Asked
Active
Viewed 129 times
1 Answers
2
From Check if passed argument is file or directory in BASH.
The following script should do the trick.
#!/bin/bash
PASSED=$1
if [[ -d $PASSED ]]; then
echo "$PASSED is a directory"
elif [[ -f $PASSED ]]; then
echo "$PASSED is a file"
else
echo "$PASSED is not valid"
exit 1
fi
Double square brackets is a bash extension to [ ]
. It doesn't require variables to be quoted, not even if they contain spaces.
Also worth trying: -e
to test if a path exists without testing what type of file it is.
-
Hello. Thanks for the response. That works well. How would I also be able to list the contents of the directory within the same script? – Teima Aug 10 '14 at 03:29
-
1You could put in a ls to list the contents of the directory. I do believe that I answered your question of how to check to see if a file is a directory. – Wyetro Aug 10 '14 at 03:31
-
2Once you have checked that a directory exists, you can then further check with `-r` that it is readable to the current user. If so, then you can list the contents with the `ls` command (generally either plain `ls` or `ls -1` (that's -ONE) when used within a script) – David C. Rankin Aug 10 '14 at 03:37