简体   繁体   中英

Bash variable expansion

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM