문제

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

도움이 되었습니까?

해결책

$ 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

다른 팁

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"

I'm sure someone will provide something better, but

case "$dirs" in (*" "*) dirs="${dirs% *}" ;; (*) dirs="" ;; esac
 $ 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]}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top