unixpathdirectoryexists

Shell script to check dir directory if it exists then change the path, if not then create dir with that name and also check for file name not exists


How to write a Shell script to check a directory and if it exists then change the path, if not then create dir with that name?(Using nano editor)


Solution

  • To check if a directory exists you can use the below test:

    [ ! -d "$DIRNAME" ]
    

    The complete script:

    if [ ! -d "${DIRNAME}" ]; then
       mkdir ${DIRNAME}
    fi
    cd ${DIRNAME}
    

    Another solution could be create however the directory with -p option that does not return error if it exists:

    mkdir -p ${DIRNAME}
    cd ${DIRNAME}