简体   繁体   English

Bash 变量扩展

[英]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.如果可能的话,我更喜欢没有 if 语句的单行方法。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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