bashdirectorypathbasename

Get the name of the folder from a path with whitespace


I'm new to bash and I'd like to know how to print the last folder name from a path.

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

Where dir is the last directory in the path. It should print as

some other folder

Instead I get:

Winchester
stuff
a
b
c
some
other
folder

I understand that spaces are causing problems ;) Do I need to pipe the result to a string and then replace newlines? Or perhaps a better way...


Solution

  • When dealing with whitespaces, all variables should be double-quoted when passed as command line arguments, so bash would know to treat them as a single parameter:

    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"
    

    This is how variable expansion occurs in 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"