Page 1 of 1
Forum

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.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



MacOS - Terminal - ...
 
Share:
Notifications
Clear all

[Solved] MacOS - Terminal - Script to check if a directory exists

1 Posts
1 Users
0 Reactions
11.6 K Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

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

   
ReplyQuote
Share: