Creative crypter
Creative crypter

Reputation: 1516

shell script - creating folder structure

I wrote this little shell script(test.sh) to create a basic folder structure:

#!/bin/bash

# Check if directory already exists,
# if it doesnt, create one.
if [ ! -d "~/.dir1" ]; then
        mkdir ".dir1"
else
        rm -rf ".dir1"
        mkdir ".dir1"
fi

When I run

test.sh

in console, the hidden folder is created.

But: When I run it again it tells me:

mkdir: .dir1: File exists

But it could exist because I removed it in my shell script before I created a new one! So why does it display this message?

Thanks and greetings!

Upvotes: 2

Views: 4363

Answers (4)

hek2mgl
hek2mgl

Reputation: 158250

I would simply use -p.

mkdir -p "$HOME/dir1"

If you pass -p, mkdir wouldn't throw an error if the directory already exists, it would simply silently return in that case.

If you want to make sure folder is empty use this:

rm -rf "$HOME/dir1"
mkdir -p "$HOME/dir1"

and no if! The basic problem with the if is the fact that it is not immune against race conditions. When the script went off from CPU right after the if - and creates "dir1" - your script will fail when it enters the CPU again since it still thinks the directory does not exist.

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 362157

~ isn't expanded when you place it in quotes. You need to leave it unquoted.

if [ ! -d ~/.dir1 ]

Of note, you're checking for ~/.dir1 but you make .dir1. That's only the same directory if the current directory is ~. If it isn't, they're not the same.

Also, mkdir -p will do this for you, creating a directory only if it doesn't exist already. You could simplify your script to:

mkdir -p ~/.dir1

or

rm -rf ~/.dir1
mkdir ~/.dir1

Upvotes: 1

Jahid
Jahid

Reputation: 22448

What you are doing by "~/.dir1" is not right. It's just another string for a directory name literally "~/.dir1" i.e ~ is not being expanded to $HOME.

Use full path or ~/".dir1" or ~/.dir1 instead.

You can use $HOME too: $HOME/.dir1 or "$HOME/.dir1" or "$HOME"/".dir1" all of them will produce same result... but quoting variables is a good practice.

Upvotes: 1

Cyrus
Cyrus

Reputation: 88999

Replace

[ ! -d "~/.dir1" ]

by

[ ! -d "${HOME}/.dir1" ]

Upvotes: 2

Related Questions