I have a script where I want to list USB devices using the command lsblk
.
The command:
$ lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb
which results in
sdb usb Kingston DataTraveler 2.0
sdc usb Kingston DT 101 G2
I want to save the result in a variable to work later, so I write
$ usbs=$(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)
What I was expecting is that the variable usbs
stores the result in two whole lines like above. But if I run:
for i in ${usbs[@]}; do
echo $i
done
I get the result split into words:
sdb
usb
Kingston
DataTraveler
2.0
sdc
usb
Kingston
DT
101
G2
Question:
Is there a way in which, using the grep
command, I can store the result of the command as two whole lines?
I prefer to know if there's a simple solution instead of dumping the result in a file and then read it.
echo "${#usbs[@]}"
to see the number of items in theusbs
"array", or"${!usbs[@]}"
to list its indices. Or print it withecho "$usbs"
. It is likely storing what you are expecting it to. – fra-san May 15 '19 at 20:18$(...)
constructs) when you reference them and the shell will keep your whitespace intact. But be aware the shell won't automatically assign array elements based on newlines. It will still be one string, just with a newline in the middle. – Chris Davies May 15 '19 at 20:28var=$(...)
is equivalent tovar="$(...)"
– jesse_b May 15 '19 at 22:53