1

How can I rewrite the following bash command to be ShellCheck compliant?

memory=$(cat /proc/meminfo | grep 'MemTotal:' | awk {'print $2}' 2> /dev/null)

It is currently complaining about:

  • Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..'
  • This { is literal.
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Justin
  • 42,716
  • 77
  • 201
  • 296
  • I think you meant 'useless' instead of 'unless' (Consider cut&pasting the errors in future). I've edited it to suit. Have you considered making those changes that were suggested by the tool? – Arafangion Aug 16 '17 at 01:18

2 Answers2

7

The shellcheck complaints are

  • Using cat filename | grep 'pattern' instead of grep 'pattern' filename
  • The first brace in the awk command is on the outside of the single quote, hence literal; it should be awk '{command}'

So, a version that would satisfy shellcheck would look like

memory=$(grep 'MemTotal:' /proc/meminfo | awk '{print $2}')

I'm not sure why you redirected standard error, so I dropped it.

However, piping grep output to awk is rarely the best solution; awk can do almost anything grep can, so you could further simplify to

memory=$(awk '/MemTotal:/ { print $2 }' /proc/meminfo)

No pipes!

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
2

Just as a guess, you probably want:

memory=$(grep 'MemTotal:' /proc/meminfo | awk '{print $2}' 2> /dev/null)

However, that's a direct interpretation of the shellcheck output, so I am unsure as to what you are asking about. As it stands, you are essentially asking: "Why isn't this working?".

Arafangion
  • 11,517
  • 1
  • 40
  • 72