0

I do feel stupid, but can someone please explain to me, why this:

current="`smartctl -a /dev/sda | awk '/Serial Number/ {printf "%s%s%s %s ", "\033[31m","/dev/sda","\033[0m",$3}'`"
current2="`$current | awk '{print $2}'`"

leads to "/dev/sda: No such file or directory" while this:

current2="`smartctl -a /dev/sda | awk '/Serial Number/ {printf "%s%s%s %s ", "\033[31m","/dev/sda","\033[0m",$3}' | awk '{print $2}'`"

is working and this one:

current="`smartctl -a /dev/sda | awk '/Serial Number/ {printf "%s%s%s %s ", "\033[31m","/dev/sda","\033[0m",$3}'`"
current2="`echo $current | awk '{print $2}'`"

also working

Dante4
  • 13
  • 3
  • A good read which could solve your problems https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script – Jetchisel May 02 '21 at 19:04
  • The problem is that the things in a pipeline (`thing1 | thing2`) must be *commands* (like `echo $current` and `awk '{print $2}'`), not just pieces of data (like just `$current`). When you use `$current | ...`, the shell tries to treat the content of `$current` as a command, and it fails. Also, you should double-quote variable references to avoid weird parsing problems (e.g. `echo "$current"` instead of just `echo $current`). [shellcheck.net](https://www.shellcheck.net) will spot some of these problems, and also have other useful suggestions. – Gordon Davisson May 02 '21 at 20:33
  • Two of the shell programming fundamentals you're currently missing are described at https://mywiki.wooledge.org/Quotes and http://mywiki.wooledge.org/BashFAQ/082. – Ed Morton May 02 '21 at 23:03

1 Answers1

0

In the first code, current stores the result of the code inside `...`, and as a result, has the string something like /dev/sda 502....

In the subsequent line, you have `$current` | awk .... Now, when the shell sees this, it replaces $current with the string /dev/sda ... and tries to run it; i.e., you are in effect asking the shell to execute /dev/sda 502..., which leads to an error.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • But both $current and awk inside `` – Dante4 May 02 '21 at 20:13
  • Yes, but that does not change the analyiss. You are trying to _execute_ `/dev/sda ... | awk ...`, which does not make sense. This is analogous to that you're trying `input.txt | awk ...`. You would rather want `cat input.txt | awk ...` or `awk ... input.txt`. You don't just write the name of an input file (or in your case the input variable `$current`) as a _command_. – j1-lee May 02 '21 at 20:31
  • Roger, thank you, for spending time on helping me – Dante4 May 02 '21 at 20:36
  • You're very welcome! Glad it helped. – j1-lee May 02 '21 at 20:47