0

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
1
  • What kind of function ? Parameter ? I don't want to use if condition but case with a lot of test on directory/file. Commented Oct 21, 2014 at 12:29

2 Answers 2

4

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...

Sign up to request clarification or add additional context in comments.

1 Comment

[ is a built-in as well as an external program. See type -a [.
1

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

1 Comment

The idea is to get a bash script with the output : The file /etc is an directory "/etc" is accessible by root read-write The /etc/passwd file is a regular file that is not empty "/etc/passwd" is accessible by toto read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.