1

I have a string made up of directories with a space after each one

dirs="/home /home/a /home/b /home/a/b/c"

the following code deletes the last directory in the string.

dirs=${dirs% * }

This works in all cases except when only one directory is in the string, then it doesn't delete it because it doesn't have a space before it.
I'm sure there's an easy way to fix this, but i'm stuck.
I'd prefer a one line method without if statements if possible.

thanks

DanielST
  • 13,783
  • 7
  • 42
  • 65

4 Answers4

3
$ dirs="/home /home/a /home/b /home/a/b/c"
$ dirsa=($dirs)
$ echo "${dirsa[@]::$((${#dirsa[@]}-1))}"
/home /home/a /home/b
$ dirs="${dirsa[@]::$((${#dirsa[@]}-1))}"
$ echo "$dirs"
/home /home/a /home/b
$ dirs="/home"
$ dirsa=($dirs)
$ dirs="${dirsa[@]::$((${#dirsa[@]}-1))}"
$ echo "$dirs"

Or, you know, just keep it as an array the whole time.

$ dirs=(/home /home/a /home/b /home/a/b/c)
$ dirs=("${dirs[@]::$((${#dirs[@]}-1))}")
$ echo "${dirs[@]}"
/home /home/a /home/b
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

First, delete any non-spaces from the end; then, delete any trailing spaces:

dirs="/home /home/a /home/b /home/a/b/c"
dirs="${dirs%"${dirs##*[[:space:]]}"}" && dirs="${dirs%"${dirs##*[![:space:]]}"}"
echo "$dirs"
phron
  • 11
  • 1
  • wow, that's making my brain hurt. I'm short on time atm but i'll figure it out later and use ignacio's now. thanks though – DanielST Apr 28 '11 at 18:26
0

I'm sure someone will provide something better, but

case "$dirs" in (*" "*) dirs="${dirs% *}" ;; (*) dirs="" ;; esac
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0
 $ dirs="/home /home/a /home/b /home/a/b/c"
 $ [[ $dirs =~ '(.*) (.[^ ]*)$' ]]
 $ echo ${BASH_REMATCH[1]}
 /home /home/a /home/b
 $ dirs="/home"
 [[ $dirs =~ '(.*) (.[^ ]*)$' ]]
 $ echo ${BASH_REMATCH[1]}
ghostdog74
  • 327,991
  • 56
  • 259
  • 343