在 case 语句中使用 grep 命令

Using grep command inside case statement

所以我有这个脚本,我试图确定文件的类型并采取相应的行动,我正在使用文件命令确定文件的类型,然后对特定字符串进行 grep,例如,如果文件被压缩,那么解压它,如果它被 gzipped 然后 gunzip 它,我想添加很多不同类型的文件。

我正在尝试用 case 替换 if 语句,但无法弄清楚

我的脚本如下所示:

##$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

感谢所有帮助过的人:)

一般语法是

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

因此对于您的代码段,

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

如果您想先将 file 输出捕获到一个变量中,当然可以这样做;但是 avoid upper case for your private variables.

不过,

bzip2unzip 默认修改它们的输入文件。也许您想避免这种情况?

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

另请注意 shell 如何方便地让您输出(输入)条件语句。