Bash 脚本 - 文件目录不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42931699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:55:03  来源:igfitidea点击:

Bash script - File directory does not exist

bash

提问by imprudent student

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

我正在创建一个非常简单的 bash 脚本,它将检查目录是否存在,如果不存在,则创建一个。

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
="/media/student/System"

if [ ! -d  ]
then

    mkdir 
fi

Here is the command line error:

这是命令行错误:

./test1.sh: line 2: =/media/student/System: No such file or directory

回答by yunzen

Try this

尝试这个

#!/bin/bash

directory="/media/student/System"

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

or even shorter with the parentargument of mkdir (manpage of mkdir)

甚至更短parent的 mkdir 参数( mkdir 的联机帮助页

#!/bin/bash

directory="/media/student/System"
mkdir -p "${directory}"

回答by 0.sh

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

在 bash 中,您不允许以数字或符号开头,但下划线除外_。在您使用的代码中$1,您所做的尝试分配"/media/student/System"$1,我想您可能误解了 bash 中的参数是如何工作的。我想这就是你想要的

#!/bin/bash
directory="" # 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

这段代码的作用是检查“/media/student/System”是否是目录,如果不是目录,则创建目录