在bash中,文件操作符(-f)是否可以不区分大小写?

时间:2010-07-09 08:34:04

标签: bash case-insensitive

我正在做以下事情:

if [ -f $FILE ] ; then
    echo "File exists"
fi

但我希望-f不区分大小写。也就是说,如果FILE是/etc/somefile,我希望-f识别/Etc/SomeFile

我可以用glob来部分解决它:

shopt -s nocaseglob
TARG='/etc/somefile'

MATCH=$TARG*    #assume it returns only one match

if [[ -f $MATCH ]] ; then
    echo "File exists" 
fi

但不区分大小写的globbing仅适用于文件名部分,而不适用于完整路径。因此,如果TARG为/Etc/somefile,它将无效。

有没有办法做到这一点?

6 个答案:

答案 0 :(得分:10)

问题是您的文件系统区分大小写。文件系统只提供了两种获取文件的相关方法:要么指定精确的区分大小写的文件名并检查其存在方式,要么读取目录中的所有文件,然后检查每个文件是否与模式匹配。 / p>

换句话说,检查区分大小写的文件系统上是否存在不区分大小写的文件是非常低效的。 shell可能会为你做,但在内部它会读取所有目录的内容并根据模式检查每个目录。

鉴于这一切,这有效:

if [[ -n `find /etc -maxdepth 1 -iname passwd` ]]; 
    then echo "Found";
fi

但除非您想要从'/'开始搜索所有内容,否则您必须单独检查路径的组成部分。没有办法解决这个问题;你不能在区分大小写的文件系统上神奇地检查整个路径的大小写不敏感匹配!

答案 1 :(得分:1)

不知道如何仅使用shell评估。 但是grep可以不区分大小写,因此调用grep,find和wc的脚本可能会满足您的需求。

答案 2 :(得分:0)

您可以使用nocasematch选项

shopt -s nocasematch
for file in *
do
  case "$file" in
   "/etc/passWd" ) echo $file;;
  esac
done 

答案 3 :(得分:0)

如果文件系统不区分大小写,通常很难做到这一点。基本上你已经分别迭代每个祖先目录。这是Python的一个起点:

import os

def exists_nocase(path):
    if os.path.exists(path):
        return True
    path = os.path.normpath(os.path.realpath(os.path.abspath(unicode(path)))).upper()
    parts = path.split(os.sep)
    path = unicode(os.path.join(unicode(os.path.splitdrive(path)[0]), os.sep))
    for name in parts:
        if not name:
            continue
        # this is a naive and insane way to do case-insensitive string comparisons:
        entries = dict((entry.upper(), entry) for entry in os.listdir(path))
        if name in entries:
            path = os.path.join(path, entries[name])
        else:
            return False
    return True

print exists_nocase("/ETC/ANYTHING")
print exists_nocase("/ETC/PASSWD")

答案 4 :(得分:0)

cd /etc
# using FreeBSD find
find -x -L "$(pwd)" -maxdepth 1 -type f -iregex "/EtC/[^\/]*" -iname paSSwd 

答案 5 :(得分:0)

这是使用Bash的起点:

#  fci -- check if file_case_insensitive exists 
# (on a case sensitive file system; complete file paths only!)

function fci() {   

declare IFS checkdirs countslashes dirpath dirs dirstmp filepath fulldirpaths i name ndirs result resulttmp

[[ -f "$1" ]] && { return 0; }
[[ "${1:0:1}" != '/' ]] && { echo "No absolute file path given: ${1}" 2>&1; return 1; }
[[ "$1" == '/' ]] && { return 1; }

filepath="$1"
filepath="${filepath%"${filepath##*[!/]}"}"  # remove trailing slashes, if any
dirpath="${filepath%/*}"
name="${filepath##*/}"

IFS='/'
dirs=( ${dirpath} )

if [[ ${#dirs[@]} -eq 0 ]]; then
   fulldirpaths=( '/' )
   ndirs=1
else
   IFS=""
   dirs=( ${dirs[@]} )
   ndirs=${#dirs[@]}

   for ((i=0; i < ${ndirs}; i++)); do

      if [[ $i -eq 0 ]]; then
         checkdirs=( '/' )
      else
         checkdirs=( "${dirstmp[@]}" )
      fi

      IFS=$'\777'
      dirstmp=( $( find -x -L "${checkdirs[@]}" -mindepth 1 -maxdepth 1 -type d -iname "${dirs[i]}" -print0 2>/dev/null | tr '\0' '\777' ) )

      IFS=""
      fulldirpaths=( ${fulldirpaths[@]} ${dirstmp[@]} )

   done

fi

printf "fulldirpaths: %s\n" "${fulldirpaths[@]}" | nl

for ((i=0; i < ${#fulldirpaths[@]}; i++)); do
   countslashes="${fulldirpaths[i]//[^\/]/}"
   [[ ${#countslashes} -ne ${ndirs} ]] && continue
   IFS=$'\777'
   resulttmp=( $( find -x -L "${fulldirpaths[i]}" -mindepth 1 -maxdepth 1 -type f -iname "${name}" -print0 2>/dev/null | tr '\0' '\777' ) )
   IFS=""
   result=( ${result[@]} ${resulttmp[@]} )
done

IFS=""
result=( ${result[@]} )

printf "result: %s\n" "${result[@]}" | nl

if [[ ${#result[@]} -eq 0 ]]; then
   return 1
else
   return 0
fi
}


FILE='/eTC/paSSwD'

if fci "${FILE}" ; then
   echo "File (case insensitive) exists: ${FILE}" 
else
   echo "File (case insensitive) does NOT exist: ${FILE}" 
fi