fun with Bash #3

Posted on

Last week I was playing around with Bash and I had this function:

# 新規フォルダの作成
function make_folder() {
	# new_path='../sh/benji/'
	FOLDER=$1
	if [ ! -d $FOLDER ]
	then
		mkdir $FOLDER
		echo "$FOLDER を作成しました。"
	else
		echo "エラー: フォルダは既存されています。"
	fi
	
}

make_folder

My output was always this:

echo “エラー: フォルダは既存されています。”

Could not understand why, maybe it was because in my terminal I kept typing the path to create my folder was wrong? Later this morning I realized I had capsulated everything in my script into functions, and that the parameter in my function above would always be overwritten above by the global variable I had created earlier:

test_val_three=${1-benji}

Also when I call the function I didn’t pass any parameters so that was also the other issue. To fix that I just moved my variable to be global and my script then became this:

#!/bin/sh
FOLDER=${1-benji}

# ...

# 新規フォルダの作成
function make_folder() {
	if [ ! -d $FOLDER ]
	then
		mkdir $FOLDER
		echo "$FOLDER を作成しました。"
	else
		echo "エラー: フォルダは既存されています。"
	fi
	
}
make_folder $FOLDER

now my output becomes:

etc@benjamin.lo% ./test.sh test
test を作成しました。

when I hit the same command again to create a folder of the same name the error finally works to show:

etc@benjamin.lo% ./test.sh test
エラー: フォルダは既存されています。

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s