我正在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 ?


当前回答

另一个重要的细节是,你不能在内部使用else和另一个if:

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在没有其他命令时使用

仅仅因为你能做某件事,并不意味着你应该一直做下去

其他回答

使

if [ "$file" == "*.txt" ]

是这样的:

if [[ $file == *.txt ]]

也就是说,只有双括号,没有引号。

==的右侧是一个外壳模式。 如果需要正则表达式,则使用=~ then。

我猜'$PATH_TO_SOMEWHERE'是类似于'<目录>/*'。

在这种情况下,我将代码更改为:

find <directory> -maxdepth 1 -type d -exec ... \;
find <directory> -maxdepth 1 -type f -name "*.txt" -exec ... \;

如果你想对目录和文本文件名做一些更复杂的事情,你可以:

find <directory> -maxdepth 1 -type d | while read dir; do echo $dir; ...; done
find <directory> -maxdepth 1 -type f -name "*.txt" | while read txtfile; do echo $txtfile; ...; done

如果文件名中有空格,你可以:

find <directory> -maxdepth 1 -type d | xargs ...
find <directory> -maxdepth 1 -type f -name "*.txt" | xargs ...

类似于'file',使用稍微简单一点的'mimetype -b',无论文件扩展名是什么都可以。

if [ $(mimetype -b "$MyFile") == "text/plain" ]
then
  echo "this is a text file"
fi

编辑:如果mimetype不可用,您可能需要在系统上安装libfile-mimeinfo-perl

如果您实际上想要查找有关文件的信息,而不是依赖于扩展名,则可以使用“file”命令。

如果您对使用扩展感到满意,您可以使用grep来查看它是否匹配。

这个答案的大部分归功于@Jox,尽管我发现(js)匹配的是.json文件,所以我添加了一个eol字符,以更充分地匹配扩展名。

$file不需要加引号,因为[[]]不会展开,所以空格不是问题(来源:Hontvári Levente)

if [[ $file =~ .*\.(js$|json$) ]]; then
  echo "The extension of '$file' matches .js|.json";
fi