'shell linux is it possible to treat variable assignation contained into a string?
I wonder if it’s possible in shell to use variable declared into a string ?
I dont know how to be explicit so here is my problem :
I use raspi-gpio for drive gpio, and i want to know states of one GPIO example :
raspi-gpio get 21
return a string :
GPIO 21: level=0 fsel=0 func=INPUT
Into this string there is level=0; fsel=0 and func=INPUT that are like variable declaration for shell.
My question :
Is it possible with minimum line to treat this 3 declarations as variable, for direct use :
if $level == 0 then...
Solution 1:[1]
Assuming command raspi-gpio get 21 returns GPIO 21: level=0 fsel=0 func=INPUT
We can delete unneeded GPIO 21: in front by "splitting" it from colon (:) character.
Then pipe the output to next command to replace space with newline.
So we have this command:
GPIO_OUTPUT=`raspi-gpio get 21`
MYCMD=`echo $GPIO_OUTPUT | cut -d':' -f2 | tr ' ' '\n'`
output of echo -e "$MYCMD" would be:
level=0
fsel=0
func=INPUT
This already looks like a valid bash variable assignment, so we can just source it:
source <(echo -e $MYCMD)
Complete code:
GPIO_OUTPUT=`raspi-gpio get 21`
MYCMD=`echo $GPIO_OUTPUT | cut -d':' -f2 | tr ' ' '\n'`
source <(echo -e $MYCMD)
if [ $level -eq 0 ] ; then
echo "level is zero"
fi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kristian |
