bash 如何使用带有空格的路径执行 mkdir?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13733843/
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-09 23:04:02  来源:igfitidea点击:

How to do mkdir with a path that has spaces?

bash

提问by Barney

I have a bash beginner problem:
My path to be created is /Volumes/ADATA\ UFD/Programming/Qt, where /Volumes/ADATA\ UFDexists already. I'd like to write a script in the following form:

我有一个 bash 初学者问题:
我要创建的路径是/Volumes/ADATA\ UFD/Programming/Qt,其中/Volumes/ADATA\ UFD已经存在。我想以以下形式编写脚本:

# create a single output directory 
outputdir="/Volumes/ADATA\ UFD/Programming/Qt"
mkdir -pv $outputdir

My problem is that mkdircreates the directory /Volumes/ADATAand ./UFD/Programminginstead of creating /Volumes/ADATA\ UFD/Programming/Qt.

我的问题是mkdir创建目录/Volumes/ADATA./UFD/Programming不是创建/Volumes/ADATA\ UFD/Programming/Qt.

I have looked at this question on SO; however, none of these solutions worked:

在 SO 上看过这个问题;但是,这些解决方案都没有奏效:

outputdir=/Volumes/"ADATA\ UFD/Programming/Qt"
mkdir -pv $outputdir

outputdir=/Volumes/'ADATA\ UFD/Programming/Qt'
mkdir -pv $outputdir

outputdir='/Volumes/ADATA\ UFD/Programming/Qt'
mkdir -pv $outputdir

outputdir=/Volumes/ADATA' 'UFD/Programming/Qt
mkdir -pv $outputdir

What am I doing wrong? What is the good combination here?

我究竟做错了什么?这里的好组合是什么?

回答by jordanm

You need to quote the variables when you use them. Expanded variables undergo wordsplitting. It's good practice to always quote your expansion, regardless of whether or not you expect it to contain special characters or spaces. You also do not need to escape spaces when quoting.

使用变量时需要引用变量。扩展的变量进行分词。无论您是否希望它包含特殊字符或空格,始终引用您的扩展是一种很好的做法。引用时也不需要转义空格。

The following will do what you want:

以下将执行您想要的操作:

outputdir='/Volumes/ADATA UFD/Programming/Qt'
mkdir -pv "$outputdir"

回答by Jonathan Leffler

Double quotes around the variable when passed to the mkdircommand:

传递给mkdir命令时,变量周围的双引号:

mkdir -pv "$outputdir"