-2

So I have this script which im trying to determine the type of the file and act accordingly, I am determining the type of the file using file command and then grep for specific string , for example if the file is zipped then unzip it, if its gzipped then gunzip it, I want to add a lot of different types of file.

I am trying to replace the if statements with case and can't figure it out

My script looks like this:

##$arg is the file itself 

TYPE="$(file $arg)"

if [[ $(echo $TYPE|grep "bzip2") ]] ; then

 bunzip2 $arg

elif [[ $(echo $TYPE|grep "Zip") ]] ; then

  unzip $arg

fi

Thanks to everyone that help :)

BryanK
  • 1,211
  • 4
  • 15
  • 33
tzahiman1
  • 3
  • 1
  • 1
    Can you show the attempt you made at using a case statement ? – BryanK Apr 03 '22 at 14:59
  • I don't know how to do it with case statement, I can only find case statement which checks the string inside the variable but not grep a specific word inside the string – tzahiman1 Apr 03 '22 at 15:07
  • no because I'm trying to write a script that gets a file , then it need to determine the file type , $arg is the file name and $TYPE is the output from file command . so im trying to grep a word inside the $TYPE – tzahiman1 Apr 03 '22 at 15:14
  • Does this answer your question? [grep statement is not working inside case statement](https://stackoverflow.com/questions/46581564/grep-statement-is-not-working-inside-case-statement) ---- Anyway apart from readability there is not much reason to use a `case` statement over multiple `if` `elif` statements – BryanK Apr 03 '22 at 15:15
  • This is part of an exercise and I must do it using case , also this is not very good practice to use 10+ if and elif statements – tzahiman1 Apr 03 '22 at 15:17
  • `case $TYPE in *bzip2*) ...` -- the `*`s make it match anywhere in the string, just like your current grep usage does. Note that this _does not_ require calling grep 10 times, which would be very bad practice itself. – Charles Duffy Apr 03 '22 at 15:29
  • 1
    By the way, all upper case variable names are used by the shell and system utilities; you should choose lowercase names for your own variables. – Charles Duffy Apr 03 '22 at 15:29

1 Answers1

4

The general syntax is

case expr in
  pattern) action;;
  other) otheraction;;
  *) default action --optional;;
esac

So for your snippet,

case $(file "$arg") in
  *bzip2*) bunzip2 "$arg";;
  *Zip*)   unzip "$arg";;
esac

If you want to capture the file output into a variable first, do that, of course; but avoid upper case for your private variables.

bzip2 and unzip by default modify their input files, though. Perhaps you want to avoid that?

case $(file "$arg") in
  *bzip2*) bzip2 -dc <"$arg";;
  *Zip*)   unzip -p "$arg";;
esac |
grep "stuff"

Notice also how the shell conveniently lets you pipe out of (and into) conditionals.

tripleee
  • 175,061
  • 34
  • 275
  • 318