Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In bash, can the file operator (-f) be case-insensitive?

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?

like image 587
Paul Richter Avatar asked Jul 09 '10 08:07

Paul Richter


People also ask

How do you make a case insensitive in bash?

Making bash autocomplete case insensitive is a small and easy way to make your Linux terminal experience much smoother. For reverting the changes, you can simply edit the inputrc file and delete the set completion-ignore-case On line.

Are bash arguments case sensitive?

Variables in Bash Scripts are untyped and declared on definition. Bash also supports some basic type declaration using the declare option, and bash variables are case sensitive.

What does F mean in bash?

-f - file is a regular file (not a directory or device file)

How do you do a case insensitive search in Linux?

Case-insensitive file searching with the find command The key to that case-insensitive search is the use of the -iname option, which is only one character different from the -name option. The -iname option is what makes the search case-insensitive.


1 Answers

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!

like image 107
Borealid Avatar answered Nov 15 '22 19:11

Borealid