I am working on restructuring the folder structure of few existing folders. So if there are any folders missed i will have to add it.

First am checking if the directory exists or not with if command, if not present am creating one. As it is case sensitive, am ending up creating same folder again.

Example : A Folder with ABC already exists but am checking with abc, so again a new folder is created with abc, sometimes folder exists with Abc.


Instead of

if [ -d abc ] ; then
    echo 'Directory exists'


if /bin/ls -d [aA][bB][cC]/ &> /dev/null ; then
    echo 'Directory exists'

In bash:

shopt -s nullglob nocaseglob
set -- [a]bc/
if [ "$#" -gt 0 ]; then
    echo 'There is at least one directory called "abc" (case ignored):'
    printf '\t%s\n' "$@"

The two bash shell options nullglob and nocaseglob are used here to test whether any directory matching the pattern [a]bc/ exists case-insensitively. The nullglob option ensures that the pattern expands to an empty string if there is no match, and the nocaseglob makes pattern matches case insensitive.

We use [a]bc/ instead of just abc to invoke filename matching against directories only. With [a] we force the shell to glob and pick up all matching names (not just abc, which, since we are doing case-insensitive globbing, may not actually exist) and with the trailing / we restrict the match to directories only. (abc or abc/ would be set as-is, with no globbing.) Doing this as an argument to set sets the positional parameters to the matching directory names. These are then available in $@ and the number of matches is found in $#.


$ mkdir abc aBc ABc   # create three directories with only case diffs in their names
$ touch abC           # ... and also a file

$ bash ./script.sh
There is at least one directory called "abc" (case ignored):
  • Indeed, thanks. I’ve added a bit more to make it explicit that [a] is needed to actually perform globbing in the first place. – Stephen Kitt Sep 13 '18 at 15:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.