views:

178

answers:

6

I'm doing the following:

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

But I want the -f to be case-insensitive. That is, if FILE is /etc/somefile, I want -f to recognize /Etc/SomeFile.

I can partially work around it with glob:

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

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

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

but the case-insensitive globbing works only on the filename portion, not the full path. So it won't work if TARG is /Etc/somefile.

Is there any way to do this?

A: 

not knowing howto only using shell evaluations. but grep can be case-insensitive, therefore a script that invokes grep , find and wc may meet your demand.

jokester
A: 

you can use the nocasematch option

shopt -s nocasematch
for file in *
do
  case "$file" in
   "/etc/passWd" ) echo $file;;
  esac
done 
ghostdog74
I don't think this works since the glob doesn't return absolute paths.
Philipp
+3  A: 

The problem is that your filesystem is case-sensitive. The filesystem provides only two relevant ways to get a file: either you specify an exact, case-sensitive filename and check for its existence that way, or you read all the files in a directory and then check if each one matches a pattern.

In other words, it is very inefficient to check if a case-insensitive version of a file exists on a case-sensitive filesystem. The shell might do it for you, but internally it's reading all the directory's contents and checking each one against a pattern.

Given all that, this works:

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

BUT you unless you want to search everything from '/' on down, you must check component of the path individually. There is no way around this; you can't magically check a whole path for case-insensitive matches on a case-sensitive filesystem!

Borealid
`find / -iwholename` would probably also work, but would be grossly inefficient.
Philipp
@Philipp: yeah, as I said, "unless you want to search everything from '/' on down"... And if you have any circular symlinks, pray...
Borealid
A: 

This is very hard to do in general if the file system is case-insensitive. Basically you have do iterate over each of the ancestor directories separately. Here is a starting point in 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")
Philipp
A: 
cd /etc
# using FreeBSD find
find -x -L "$(pwd)" -maxdepth 1 -type f -iregex "/EtC/[^\/]*" -iname paSSwd 
carlo
A: 

And here's a starting point using 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
juan