1

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.

Stephen Kitt
  • 434,908
Rob Michiels
  • 197
  • 1
  • 3
  • 11

1 Answers1

2

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"
Bart
  • 2,221
  • 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: https://unix.stackexchange.com/a/68748/357628 – Bart Jun 14 '19 at 13:35