Gho*_*ool 0 directory bash path basename
我是 bash 的新手,我想知道如何从路径打印最后一个文件夹名称。
mypath="/Users/ckull/Desktop/Winchester stuff/a b c/some other folder/"
dir="$(basename $mypath)"
echo "looking in $dir"
Run Code Online (Sandbox Code Playgroud)
其中dir是路径中的最后一个目录。它应该打印为
some other folder
Run Code Online (Sandbox Code Playgroud)
相反,我得到:
Winchester
stuff
a
b
c
some
other
folder
Run Code Online (Sandbox Code Playgroud)
我知道空格会导致问题;) 我是否需要将结果通过管道传输到字符串然后替换换行符?或者也许有更好的方法......
在处理空格时,所有变量在作为命令行参数传递时都应该用双引号引起来,因此 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"
Run Code Online (Sandbox Code Playgroud)
这就是 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"
Run Code Online (Sandbox Code Playgroud)