1

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...

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
  • I get an error message: "basename: extra operand ‘b’". So try `dir="$(basename "$mypath")"` – Wiimm Dec 02 '19 at 13:49
  • 1
    *Always* quote parameter expressions. Always. The cases where doing so is wrong is *vastly* outnumbered by the cases where it is necessary or irrelevant; quoting will save you a lot of time debugging. – chepner Dec 02 '19 at 14:08
  • Copy/paste your script into [ShellCheck](https://www.shellcheck.net/) (add a [shebang](https://stackoverflow.com/questions/10376206/what-is-the-preferred-bash-shebang) on the first line before it, e.g. `#!/usr/bin/env bash`) and it will indicate what the issue is. – RobC Dec 02 '19 at 16:01
  • I had #! /bin/bash down as the shebang. Which one is right? or is that another SO question ;) – Ghoul Fool Dec 02 '19 at 16:06
  • It's already been asked. Click the link in my previous comment. – RobC Dec 02 '19 at 16:07

1 Answers1

8

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"
Shloim
  • 5,281
  • 21
  • 36