I can't seem to figure out how I can put a fdisk command from a bash script in a multiline variable.

Here is my code

hdds="$(sudo fdisk -l | grep "Disk /dev/sd" | awk '{print$2}' | sed 's/://g')"

When I execute this bash script it puts everything on a single line like

/dev/sda /dev/sdb

When I execute this command outside of the bash script it works like it should

sudo fdisk -l | grep "Disk /dev/sd" | awk '{print$2}' | sed 's/://g' | wc -l

Where the output is 2.

I have tried putting everything in quotes, without quotes and what not but nothing seems to work.


are you calling the variable with echo, by any chance?

If so, put it in double quotes, like this:

echo "$hdds"

or use printf:

printf "%s" "$hdds"
  • 1
    Thanks! This worked. So if I understand, the variable contains 2 lines but echo without quotes makes it a one liner? – Rob Michiels Jun 14 '19 at 13:24
  • I believe this answer will give you precise answet to why, where and when quotes would work: unix.stackexchange.com/a/68748/357628 – Bart Jun 14 '19 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.