8

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
Aserre
  • 4,397
  • 3
  • 30
  • 51

2 Answers2

12

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}"
yunzen
  • 30,001
  • 10
  • 64
  • 93
  • 1
    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 – Eric Renouf Mar 21 '17 at 17:00
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

0.sh
  • 2,190
  • 14
  • 30