Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script - File directory does not exist

Tags:

bash

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
like image 829
imprudent student Avatar asked Mar 21 '17 15:03

imprudent student


People also ask

How fix bash No such file or directory?

To fix it, try the dos2unix program if you have it, or see Converting DOS Files to Linux Format. Note that if you use dos2unix it will probably create a new file and delete the old one, which will change the permissions and might also change the owner or group and affect hard links.

How do I find the bash script directory?

You can use $BASH_SOURCE : #!/usr/bin/env bash scriptdir="$( dirname -- "$BASH_SOURCE"; )"; Note that you need to use #!/bin/bash and not #!/bin/sh since it's a Bash extension.

How do you check if directory does not exist in bash?

Checking If a Directory Exists In a Bash Shell Script-h "/path/to/dir" ] && echo "Directory /path/to/dir exists." || echo "Error: Directory /path/to/dir exists but point to $(readlink -f /path/to/dir)." The cmd2 is executed if, and only if, cmd1 returns a non-zero exit status.


2 Answers

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}"
like image 99
yunzen Avatar answered Oct 08 '22 20:10

yunzen


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

like image 39
0.sh Avatar answered Oct 08 '22 18:10

0.sh