Page 1 of 1

MacOS – Terminal – Script to check if a directory exists

MacOS – Terminal – Script to check if a directory exists

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
Examples: "MacOS X - Your question", "MS Word - Your Tip or Trick".

Please note that switching to another language when reading a post will not work!
Posts will not have a translated counterpart.




RSS Feed

Home Forums Software MacOS X Software MacOS – Terminal – Script to check if a directory exists

This topic contains 0 replies, has 1 voice, and was last updated by  hans 3 weeks, 1 day ago.

Viewing 1 post (of 1 total)
  • Author
    Posts
  • 12423

    hans
    Keymaster

    I had to check if a bunch of directories were missing (because I was moving a LOT of data from my NAS to an external disk).
    Since I didn’t find an easy way, I created a small script:

    #!/bin/sh
    if [ ! -d "$1" ]
     then 
       echo $1 
    fi

    Saved it as “exists.sh” – you can store it anywhere you’d like, just remember the path to it (optionally you can add it to the $PATH environment variable, but I prefer to not do that). So I saved it in my home directory (~).

    After that I made it executable (may not be required);

    chmod +x ~/exists.sh

    Remember, I stored my script in my home directory – you may have to enter a different path depending on where you stored the file.

    Now you can test if a directory exists, by simply doing:

    ~/exists.sh /path/to/directory/you/want/to/check

    Since I want to create a list of missing directories, I’ve set it to output that path if not found.

    If you’d rather check files instead of directories, use this (-f instead of -d):

    #!/bin/sh
    if [ ! -f "$1" ]
     then 
       echo $1 
    fi

    If you’d rather check for existing directories, use this (the -f instead of -d works here as well – I removed the “!” exclamation mark):

    #!/bin/sh
    if [ -d "$1" ]
     then 
       echo $1 
    fi
Viewing 1 post (of 1 total)



You must be logged in to reply to this topic.