在bash脚本中测试文件类型并使用适当的命令解压缩它们

时间:2016-07-02 22:39:33

标签: bash scripting

到目前为止,我正在制作一个解压缩tar包以安装它们的bash脚本。我正在把tar包解压成一个直接的东西。这是脚本:

#!/Bin/bash/

# This program auto-installs tarballs for you.
# I designed this for Linux noobies who don't
# know how to install tarballs. Or, it's for
# people like me who are just lazy, and don't
# want to put in the commands ourselves.

echo "AutoTar v1.1"
echo "Gnu GPL v2.1"
read -p "Path to tarball:" pathname
cd "${pathname/#~/$HOME}"
    ls $pathname
       read -p "Please enter the file you wish to complile..." filename
if [-a $filename] == false
   then 
   echo "File does not exist! Exiting the program."
if  [[ ${filename -d} ==*.tar.gz ]]
 then
    tar -xzf $filename 
 done
else if
     [[ ${filename -d} ==*.tgz ]]
then
    tar -xzf $filename
 done
else if
   [[ ${filename -d} ==*.tar.bz2 ]]
then
    tar -xjf $filename
done
ls $pathname
echo -n "Please enter the directory of the file you have just unpacked...:"
read directory
cd $directory

我需要做的是使用if语句来检测文件并使用适当的命令,但是我不太清楚如何做到这一点。使用我当前的代码,我只是得到错误:

autotar.sh: line 18: conditional binary operator expected
autotar.sh: line 18: syntax error near `==*.tar.gz'
autotar.sh: line 18: `if  [[ ${filename -d} ==*.tar.gz ]]'

1 个答案:

答案 0 :(得分:1)

如果要检查文件是否不存在:

if [[ ! -e $filename ]]; then ## works in bash or other ksh derivatives only

...或者,为了与旧版shell兼容:

if [ ! -e "$filename" ]; then ## works in any POSIX shell

如果您想查看扩展程序:

if [[ $filename = *.tar.gz ]]; then ## works in bash or other ksh derivatives only

...或者,要检查其中一个扩展程序,请考虑使用case语句:

# this works in any POSIX shell
[ -e "$filename" ] || { echo "$filename does not exist" >&2; exit 1; }

# this, too, works in any POSIX shell
case $filename in
  *.tar.gz|*.tgz)   tar -xzf "$filename" ;;
  *.tar.bz2|*.tbz2) tar -xjf "$filename" ;;
  *.tar.xz|*.txz)   xz -d <"$filename" | tar -xv ;;
  *.zip)            unzip "$filename" ;;
 esac

特别注意:

  • 空白是必不可少的。你不能留出空间。 [ "$foo" = 1 ]是有效且正确的陈述,而[$foo=1][ "$foo" =1]是语法错误,[ "$foo"==1 ]始终返回true,无论foo具有什么值。< / LI>
  • 除了特定豁免,引用扩展对于正确的行为是强制性的。如果您不确定,安全的做法是使用它们:您可以在[[ ]]case中省略引号,只有这些引号具有使其成为可选的特殊语法规则。如果您使用的是[ ],那么您需要使用它们:if [ ! -e "$filename" ]

    但是,tar -xzf "$filename"echo "$filename"ls "$pathname"都需要空格才能正常使用有趣的文件或路径(在测试软件时尝试使用带空格的名称;带有glob字符的名称是另一个常见的潜在错误的原因,特别是在结合时)。

  • [只是test的同义词;它是一个命令,而不是特殊的语法,命令遵循正常的解析规则。就像你无法运行test$foo=false一样,你无法运行[$foo=false][-a $filename];它必须是[ -e "$filename" ]-a的POSIX规范中不存在test的一元使用,因此切换到-e)。