9

I'm creating a very simple bash script that will check to see if the directory exists, and if it doesn't, create one.

However, no matter what directory I put in it doesn't find it!

Please tell me what I'm doing wrong.

Here is my script.

#!/bin/bash
$1="/media/student/System"

if [ ! -d $1 ]
then

    mkdir $1
fi

Here is the command line error:

./test1.sh: line 2: =/media/student/System: No such file or directory
4
  • Your script stops before the if test. Your allocation is wrong. Commented Mar 21, 2017 at 15:41
  • Why do you use $1? This is a special variable: stackoverflow.com/questions/29258603/… Commented Mar 21, 2017 at 15:41
  • 1
    the correct way to do what you want would be : my_var="/media/student/System"; if[ ! -d $my_var] .... Commented Mar 21, 2017 at 15:43
  • You could have it even easier with paramater p to the mkdir command Commented Mar 21, 2017 at 15:43

2 Answers 2

14

Try this

#!/bin/bash

directory="/media/student/System"

if [ ! -d "${directory}" ]
then
    mkdir "${directory}"
fi

or even shorter with the parent argument of mkdir (manpage of mkdir)

#!/bin/bash

directory="/media/student/System"
mkdir -p "${directory}"
Sign up to request clarification or add additional context in comments.

1 Comment

Though it's not a problem in this example with this particular hard coded string, it's probably still better to always quote your variables
3

In bash you are not allow to start a variable with a number or a symbol except for an underscore _. In your code you used $1 , what you did there was trying to assign "/media/student/System" to $1, i think maybe you misunderstood how arguments in bash work. I think this is what you want

#!/bin/bash
directory="$1" # you have to quote to avoid white space splitting

if [[ ! -d "${directory}" ]];then
     mkdir "$directory"
fi

run the script like this

$ chmod +x create_dir.sh
$ ./create_dir.sh "/media/student/System"

What the piece of code does is to check if the "/media/student/System" is a directory, if it is not a directory it creates the directory

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.