So, the commands:
dmesg | grep 'Attached SCSI disk' | awk '{ print $5}'
when executed directly from shell, works like it should, outputting:
[sdb]
[sdc]
[sda]
But, when I’m launching it with:
sh -c "dmesg | grep 'Attached SCSI disk' | awk '{ print $5}'"
# or
bash -c "dmesg | grep 'Attached SCSI disk' | awk '{ print $5}'"
I get:
[ 2.460353] sd 1:0:0:0: [sdb] Attached SCSI disk
[ 2.461348] sd 2:0:0:0: [sdc] Attached SCSI disk
[ 2.464181] sd 0:0:0:0: [sda] Attached SCSI disk
That clearly shows that the last pipe has not executed.
What am I doing wrong?
Your
$5is getting evaluated too early. Change it to\$5.If you were to replace
bashwithecho, you would see that$5is being replace by the empty string:So, when bash evaluates the command, awk is going to print the entire line, not the fifth field.
When you escape the dollar sign (by pre-prending with a backslash), the variable
$5is preserved: