Reputation: 405
Hi I want to simplify my script with case
echo "The file $1 is "
if [ -f $1 ] then;
echo "an regular file"
elif [ -d $1 ] then;
echo "a directory"
fi
by something like this
case $1 in
[ -f $1 ])
echo "an regular file"
;;
[ -d $1 ])
echo "a directory"
;;
esac
Upvotes: 0
Views: 244
Reputation: 27852
This is not how case
works, in any programmming language. In case
, you have one test/expression at the top that gives a value, and depending on that value, you can do different things. The whole point of this is that you only run your test command once, and not for every elif
branch.
What you want, is just if
/elif
with a different syntax, which is sort of pointless...
If you want to simplify it, you might be able to use stat
:
case $(stat -c%F "$1") in
directory)
echo Directory; ;;
regular\ file)
echo File; ;;
esac
This has (slightly) better performance than your first example, since it only runs one external command
Bonus hint: Remember to always quote filenames, so use: [ -f "$1" ]
and not [ -f $1 ]
. Consider that 1) [
is just a shell command (a builtin or /bin/[
, makes no real difference though), and 2) $1
may contain spaces or other whitespace...
Upvotes: 4
Reputation: 786349
If you really want output like regular file
or directory
from a given file then use stat
command:
stat -c '%F' afile.txt
regular file
stat -c '%F' adirectory
directory
Upvotes: 1