Home > front end >  Using grep command inside case statement
Using grep command inside case statement

Time:04-21

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 :)

CodePudding user response:

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.

  • Related