从带有空格的路径中获取文件夹的名称

时间:2019-12-02 13:44:57

标签: bash directory path basename

我是bash的新手,我想知道如何从路径中打印上一个文件夹名称。

mypath="/Users/ckull/Desktop/Winchester stuff/a b c/some other folder/"
dir="$(basename $mypath)"
echo "looking in $dir"

其中 dir 是路径中的最后一个目录。它应该打印为

some other folder

相反,我得到了:

Winchester
stuff
a
b
c
some
other
folder

我知道空格会引起问题;)是否需要将结果通过管道传递给字符串,然后替换换行符?也许是更好的方法...

1 个答案:

答案 0 :(得分:5)

在处理空格时,所有变量在作为命令行参数传递时都应双引号,因此bash会知道将它们视为单个参数:

mypath="/Users/ckull/Desktop/Winchester stuff/a b c/some other folder/"
dir="$(basename "$mypath")" # quote also around $mypath!
echo "lookig in $dir"
# examples
ls "$dir" # quote only around $dir!
cp "$dir/a.txt" "$dir/b.txt"

这是bash中变量扩展发生的方式:

var="aaa bbb"
               # args: 0      1              2     3
foo $var ccc   # ==>   "foo"  "aaa"          "bbb" "ccc"
foo "$var" ccc # ==>   "foo"  "aaa bbb"      "ccc"
foo "$var ccc" # ==>   "foo"  "aaa bbb ccc"
相关问题