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.

3 Answers 3


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 is removed if there is no match (it is otherwise left unexpanded), 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 perform globbing and thereby pick up all matching names, and with the trailing / we restrict the matching to directories only. 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):

Instead of

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


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

In zsh, you can check whether one or more files of type directory and whose name is abc case insensitively exist with:

set -o extendedglob # best in ~/.zshrc
if () { (($#)); } (#i)abc(/N); then
  echo such directories exist

That's an invoking an anonymous function (() { body; } args) where the body is (($#)) to check that the number of arguments is non-zero, and the args is the result of the expansion of the (#i)abc(/N) glob, where (#i) turns on case insensitive matching and (/N) is a glob qualifier where / restricts to files of type directory and N enables nullglob so the glob expands to nothing when there's no match instead of reporting an error.

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.