How to write code to check if a directory with a specified name currently exists or not?

Posted on 2004-08-10
Last Modified: 2008-01-09

I'm writing some code in  Linux. In my code, I need to check if a subdirectory, say "subdir1", currently exists inside the current directory or not. If not, my code needs to create the subdir. Otherwise, don't do anything.

I don't know how to write the code to check if the subdir exists. If you know, please give some help.



Question by:rfr1tz
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 11

Expert Comment

ID: 11764767
LVL 23

Accepted Solution

brettmjohnson earned 250 total points
ID: 11764998
mkdir -p "./subdir1"

LVL 38

Expert Comment

ID: 11769780
Here's a shell script example:

cd /a-dir
if [ ! -d subdir1 ] ; then
   mkdir subdir1

PS: you can use the same systax for sh/bash script

man if

to learn more details
Cloud Training Guides

FREE GUIDES: In-depth and hand-crafted Linux, AWS, OpenStack, DevOps, Azure, and Cloud training guides created by Linux Academy instructors and the community.


Expert Comment

ID: 11770130
Providing your programming language of choice would help a lot.

Expert Comment

ID: 11877929
Hi rfr1tz,
I think every given solution is working.I am giving u one more way to do this

in ur editor, if u r in that directory write following code..

if [ ls -l | grep "^d" "dir_name" ]
mkdir <dir_name>

then change the mode of directory so that it can be executed and run . u will find it in ur listing.

if u want to search subdirectory of some directory that is in the current direcory specify it with ls

if [ ls -l <dir_name> | grep "^d" "dir_name" ]
mkdir <dir_name>

Although all above solutions are perfect and standard. It is only for beginners or manipulators.

It's a humble request now accept any one answer.

Expert Comment

ID: 12036475
If you are coding in C, then read the 'stat' man page.

man 2 stat

So, what you need is to call stat(2) for the path and then
test S_ISDIR(buf->st_mode)

   #include <sys/types.h>
   #include <sys/stat.h>
   #include <unistd.h>

  struct stat buf;
  if (stat("/path/that/you/want/to/test", &buf) == -1)
      // handle error (see below)
   if (S_ISDIR(buf.st_mode))

       stat, fstat, lstat - get file status

       #include <sys/types.h>
       #include <sys/stat.h>
       #include <unistd.h>

       int stat(const char *file_name, struct stat *buf);
       int fstat(int filedes, struct stat *buf);
       int lstat(const char *file_name, struct stat *buf);

       These  functions  return  information about the specified file.  You do
       not need any access rights to the file to get this information but  you
       need  search rights to all directories named in the path leading to the

       stat stats the file pointed to by file_name and fills in buf.

       lstat is identical to stat, except in the  case  of  a  symbolic  link,
       where the link itself is stat-ed, not the file that it refers to.

       fstat  is  identical  to stat, only the open file pointed to by filedes
       (as returned by open(2)) is stat-ed in place of file_name.

       They all return a stat structure, which contains the following fields:

              struct stat {
                  dev_t         st_dev;      /* device */
                  ino_t         st_ino;      /* inode */
                  mode_t        st_mode;     /* protection */
                  nlink_t       st_nlink;    /* number of hard links */
                  uid_t         st_uid;      /* user ID of owner */
                  gid_t         st_gid;      /* group ID of owner */
                  dev_t         st_rdev;     /* device type (if inode device) */
                  off_t         st_size;     /* total size, in bytes */
                  blksize_t     st_blksize;  /* blocksize for filesystem I/O */
                  blkcnt_t      st_blocks;   /* number of blocks allocated */
                  time_t        st_atime;    /* time of last access */
                  time_t        st_mtime;    /* time of last modification */
                  time_t        st_ctime;    /* time of last change */

       The value st_size gives the size of the file (if it is a  regular  file
       or  a  symlink)  in  bytes.  The size of a symlink is the length of the
       pathname it contains, without trailing NUL.

       The value st_blocks gives the size of  the  file  in  512-byte  blocks.
       (This  may  be  smaller than st_size/512 e.g. when the file has holes.)
       The value st_blksize gives the "preferred" blocksize for efficient file
       system  I/O.  (Writing to a file in smaller chunks may cause an ineffi-
       cient read-modify-rewrite.)

       Not all of the Linux filesystems implement  all  of  the  time  fields.
       Some  file system types allow mounting in such a way that file accesses
       do not cause an  update  of  the  st_atime  field.  (See  ‘noatime’  in

       The  field  st_atime  is  changed  by file accesses, e.g. by execve(2),
       mknod(2), pipe(2), utime(2) and read(2)  (of  more  than  zero  bytes).
       Other routines, like mmap(2), may or may not update st_atime.

       The  field st_mtime is changed by file modifications, e.g. by mknod(2),
       truncate(2), utime(2) and write(2) (of more than  zero  bytes).   More-
       over, st_mtime of a directory is changed by the creation or deletion of
       files in that directory.  The st_mtime field is not changed for changes
       in owner, group, hard link count, or mode.

       The  field  st_ctime is changed by writing or by setting inode informa-
       tion (i.e., owner, group, link count, mode, etc.).

       The following POSIX macros are defined to check the file type:

              S_ISREG(m)  is it a regular file?

              S_ISDIR(m)  directory?

              S_ISCHR(m)  character device?

              S_ISBLK(m)  block device?

              S_ISFIFO(m) fifo?

              S_ISLNK(m)  symbolic link? (Not in POSIX.1-1996.)

              S_ISSOCK(m) socket? (Not in POSIX.1-1996.)

       The following flags are defined for the st_mode field:

       S_IFMT     0170000   bitmask for the file type bitfields
       S_IFSOCK   0140000   socket
       S_IFLNK    0120000   symbolic link
       S_IFREG    0100000   regular file
       S_IFBLK    0060000   block device
       S_IFDIR    0040000   directory
       S_IFCHR    0020000   character device
       S_IFIFO    0010000   fifo
       S_ISUID    0004000   set UID bit
       S_ISGID    0002000   set GID bit (see below)
       S_ISVTX    0001000   sticky bit (see below)
       S_IRWXU    00700     mask for file owner permissions
       S_IRUSR    00400     owner has read permission
       S_IWUSR    00200     owner has write permission
       S_IXUSR    00100     owner has execute permission
       S_IRWXG    00070     mask for group permissions
       S_IRGRP    00040     group has read permission
       S_IWGRP    00020     group has write permission
       S_IXGRP    00010     group has execute permission
       S_IRWXO    00007     mask for permissions for others (not in group)
       S_IROTH    00004     others have read permission
       S_IWOTH    00002     others have write permisson
       S_IXOTH    00001     others have execute permission

       The set GID bit (S_ISGID) has several special uses: For a directory  it
       indicates  that  BSD  semantics is to be used for that directory: files
       created there inherit their group ID from the directory, not  from  the
       effective  gid  of  the creating process, and directories created there
       will also get the S_ISGID bit set.  For a file that does not  have  the
       group  execution  bit (S_IXGRP) set, it indicates mandatory file/record

       The ‘sticky’ bit (S_ISVTX) on a directory means that  a  file  in  that
       directory  can  be renamed or deleted only by the owner of the file, by
       the owner of the directory, and by root.

       On success, zero is returned.  On error, -1 is returned, and  errno  is
       set appropriately.

       EBADF  filedes is bad.

       ENOENT A component of the path file_name does not exist, or the path is
              an empty string.

              A component of the path is not a directory.

       ELOOP  Too many symbolic links encountered while traversing the path.

       EFAULT Bad address.

       EACCES Permission denied.
       ENOMEM Out of memory (i.e. kernel memory).

              File name too long.

       The stat and fstat calls conform to SVr4, SVID, POSIX, X/OPEN, BSD 4.3.
       The  lstat call conforms to 4.3BSD and SVr4.  SVr4 documents additional
       fstat error conditions EINTR, ENOLINK, and EOVERFLOW.   SVr4  documents
       additional  stat  and  lstat error conditions EACCES, EINTR, EMULTIHOP,
       ENOLINK, and EOVERFLOW.  Use of the st_blocks and st_blksize fields may
       be  less  portable. (They were introduced in BSD.  Are not specified by
       POSIX. The interpretation differs between systems, and  possibly  on  a
       single system when NFS mounts are involved.)

       POSIX  does  not  describe  the  S_IFMT,  S_IFSOCK,  S_IFLNK,  S_IFREG,
       S_IFBLK, S_IFDIR, S_IFCHR, S_IFIFO, S_ISVTX bits, but  instead  demands
       the  use  of the macros S_ISDIR(), etc. The S_ISLNK and S_ISSOCK macros
       are not in POSIX.1-1996, but both will be in the next  POSIX  standard;
       the former is from SVID 4v2, the latter from SUSv2.

       Unix V7 (and later systems) had S_IREAD, S_IWRITE, S_IEXEC, where POSIX
       prescribes the synonyms S_IRUSR, S_IWUSR, S_IXUSR.
       Values that have been (or are) in use on various systems:

       hex    name       ls   octal    description
       f000   S_IFMT          170000   mask for file type
       0000                   000000   SCO out-of-service inode, BSD unknown type
                                       SVID-v2 and XPG2 have both 0 and 0100000 for ordinary file
       1000   S_IFIFO    p|   010000   fifo (named pipe)
       2000   S_IFCHR    c    020000   character special (V7)
       3000   S_IFMPC         030000   multiplexed character special (V7)
       4000   S_IFDIR    d/   040000   directory (V7)
       5000   S_IFNAM         050000   XENIX named special file
                                       with two subtypes, distinguished by st_rdev values 1, 2:
       0001   S_INSEM    s    000001   XENIX semaphore subtype of IFNAM
       0002   S_INSHD    m    000002   XENIX shared data subtype of IFNAM
       6000   S_IFBLK    b    060000   block special (V7)
       7000   S_IFMPB         070000   multiplexed block special (V7)
       8000   S_IFREG    -    100000   regular (V7)
       9000   S_IFCMP         110000   VxFS compressed
       9000   S_IFNWK    n    110000   network special (HP-UX)
       a000   S_IFLNK    l@   120000   symbolic link (BSD)
       b000   S_IFSHAD        130000   Solaris shadow inode for ACL (not seen by userspace)
       c000   S_IFSOCK   s=   140000   socket (BSD; also "S_IFSOC" on VxFS)
       d000   S_IFDOOR   D>   150000   Solaris door
       e000   S_IFWHT    w%   160000   BSD whiteout (not used for inode)

       0200   S_ISVTX         001000   ‘sticky bit’: save swapped text even after use (V7)
                                       reserved (SVID-v2)
                                       On non-directories: don’t cache this file (SunOS)
                                       On directories: restricted deletion flag (SVID-v4.2)
       0400   S_ISGID         002000   set group ID on execution (V7)
                                       for directories: use BSD semantics for propagation of gid
       0400   S_ENFMT         002000   SysV file locking enforcement (shared w/ S_ISGID)
       0800   S_ISUID         004000   set user ID on execution (V7)
       0800   S_CDF           004000   directory is a context dependent file (HP-UX)

       A sticky command appeared in Version 32V AT&T UNIX.

       chmod(2), chown(2), readlink(2), utime(2)


Expert Comment

ID: 12156673
I think my answer is more to the point than the answer of brettmjohnson.  The author is writing
in C as you seem to agree with me (although the author of the question doesn't state so, I think
we can conclude that from the fact that he didn't accept any of the answers that are about shell
scripting at the time that this question was recent/active).  His explicit question is:

"I don't know how to write the code to check if the subdir exists"

My answer gives the best answer to that exact question.
brettmjohnson's answer gives an answer for the more general problem, but only
for shell scripting.  He doesn't mention that there exists a mkdir(2) library call
or how that could be used to simulate the -p.  His answer is 100% useless to the
author of the question (assuming he codes in C), even if you believe that mkdir(2)
would have been a more proper answer than my stat(2) (which is in fact a precise
and correct answer to his actual question).

LVL 38

Expert Comment

ID: 12156873
In shell script situation use IF to test if a dir exists before doing "mkdir" is better than
just "mkdir -p".

Any comments can be accepted as the answer in this page!

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever been frustrated by having to click seven times in order to retrieve a small bit of information from the web, always the same seven clicks, scrolling down and down until you reach your target? When you know the benefits of the command l…
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor ( Top Charts is a view in which you can set seve…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question