Linux Shell Scripting: Check if Folder Exists

If we want to check if a folder exists we simply create the following .sh file:

#!/bin/bash
 
if [ ! -d "myFolder" ]; then
	echo "Creating myFolder"
	sudo mkdir myFolder
fi
 
if [ ! -d "myFolder/subFolder" ]; then
	echo "Creating myFolder/subFolder"
	sudo mkdir myFolder/subFolder
fi

Now you can run that using sudo and for example create a new folder where one didn’t exist before, if its required by some other script, for example one mounting a windows XP drive over a network to the current Linux filesystem using Samba. See the post covering that for more details.

Comments
  • Steve

    Interesting post. I wonder what the easy way is to create the folder as you describe then automatically chmod it.

  • SD

    Hey Steve,

    An easy way would be to add the following:
    “mkdir folderName”
    “chmod -R a=wrx folderName” (use the -R option for recursively applying the chmod to all child dir’s)

  • Steve

    Thanks mate. Will give it a try :-)

Leave a Comment