user15148997
user15148997

Reputation:

To have Bash to do case insensitive operation on a test

How to have Bash to do case insensitive operation on test:

$ n=Foo
$ [ -e "$n" ] && echo $n exist

foo exist

if it is:

$ ls
foo   bar   baz

How the correct setting ?

Upvotes: 2

Views: 284

Answers (2)

Zilog80
Zilog80

Reputation: 2562

You can also use bash case insensitive global matching pattern :

$ shopt -s nocaseglob
$ shopt -s nocasematch
$ n=Foo
$ f=("$n"*)
$ [ "${f[0]/$n/}" = "" ] && echo ${f[0]} exist
foo exist

But take care that to have a conditional test matching a pattern and not directly a filename with f=("$n"*), we use here a *. With that, you'll get a wrong result if there is pattern symbols like * or ? in $n.

You have also to carefully consider the global effect of shell options (shopt -s nocaseglob, shopt -s nocasematch). Generally, to avoid unexpected behaviors in any following shell commands / scripts, you have to restore initial states of theses options. Check and store the initial state with shopt option to restore it later.

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 140970

Use ipath in find.

if tmp=$(find . -maxdepth 1 -ipath "./$n") && [[ -n "$tmp" ]]; then
   echo "$n exists and there are:" $tmp
fi

Upvotes: 0

Related Questions