Search code examples
bashshellshellcheck

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.

Solution

  • 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!