如何在Bash脚本中检查文件名的扩展名?

246
我正在编写一个Bash夜间构建脚本。除了一个小问题,一切都很好:


#!/bin/bash

for file in "$PATH_TO_SOMEWHERE"; do
      if [ -d $file ]
      then
              # do something directory-ish
      else
              if [ "$file" == "*.txt" ]       #  this is the snag
              then
                     # do something txt-ish
              fi
      fi
done;

我的问题是确定文件扩展名,然后相应地采取行动。我知道问题出在if语句中,测试txt文件。

如何确定文件是否具有.txt后缀?


如果文件名中有空格,这将会出错。 - jfg956
除了Paul的答案之外,您还可以使用$(dirname $PATH_TO_SOMEWHERE)$(basename $PATH_TO_SOMEWHERE)来拆分文件夹和目录,并执行某些目录式和文件式的操作。 - McPeppr
11个回答

0

另一个重要的细节是,您不应在另一个if内使用else

else
    if [ "$file" == "*.txt" ]       
    #  this is the snag
    then
    # do something txt-ish
fi

改为:

elif [ "$file" == "*.txt" ]       
    #  this is the snag
then
    # do something txt-ish
fi

else 是在没有其他选择时使用的关键字,意味着要执行 do 中的 thatcommand

仅仅因为你能做某件事,并不意味着你总是应该这样做


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接