简体   繁体   中英

bash scripting: combine var=$(…) and var=${var%%…} lines?

Is it possible and, if yes, how to convert the following expression to one-liner?

DEV=$(lsblk -no KNAME,MODEL | grep 'ModelNAME')
DEV=${DEV%%'ModelNAME'}

Simple DEV=${(lsblk -no KNAME,MODEL | grep 'ModelNAME')%%'ModelNAME'} doesn't work

zsh allows you to combine parameter expansions. Bash does not.

For either bash or POSIX sh (both of which support this particular parameter expansion), you'll need to do this as two separate commands.


That said, there are other options available. For instance:

# tell awk to print first field and exit on a match
dev=$(lsblk -no KNAME,MODEL | awk '/ModelNAME/ { print $1; exit }')

...or, even easier (but requiring bash or another modern ksh derivative):

# read first field of first line returned by grep; _ is a placeholder for other fields
read -r dev _ < <(lsblk -no KNAME,MODEL | grep -e ModelNAME)

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