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

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

4 Comments

cool, having a bit of difficulty figuring out whats happening though. Tell me if i'm right.
... not sure what happened to the rest of my comment. Anyways, #dirs[@] converts my string into an array of words and the -1 shortens it by one?
${#dirs[@]} gives you the length of the array. ${dirs[@]::} slices the array. So, it slices the last element off the array.
ahh, thanks. I'm coming from a c (++, #) and the syntax in linux is killing me.
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"

1 Comment

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
0

I'm sure someone will provide something better, but

case "$dirs" in (*" "*) dirs="${dirs% *}" ;; (*) dirs="" ;; esac

Comments

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]}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.