Skip to content
Advertisement

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement