Justin Justin - 1 year ago 57
Bash Question

Rewrite bash command to be ShellCheck compliant

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.

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download