Muneeb K Muneeb K - 6 months ago 18
Bash Question

Error while executing awk command in shell script

I am trying to print the memory details . Total , Free and used memory using a shell script. This is my code -

printf "\nSystem Details\n"
printf "CPU $(cat /proc/cpuinfo | grep "model name" | head -1)"

printf "Total Memory:"
printf "$(awk '/^Mem/ {print $3}' <(free -m))"


But terminal doesn't display any memory details. It shows this error.

Memory:info.sh: command substitution: line 23: syntax error near unexpected token `('
info.sh: command substitution: line 23: `awk '/^Mem/ {print $3}' <(free -m))"'

Answer

Let's run the line in question under bash:

$ printf "$(awk '/^Mem/ {print $3}' <(free -m))"
5603$ 

It works. Now let's try it under dash:

$ printf "$(awk '/^Mem/ {print $3}' <(free -m))"
dash: 1: Syntax error: "(" unexpected

Now, we see the syntax error about the unexpected (. The error is because dash does not support process substitution.

If you want to run under dash or similar shells, the solution is to use a pipeline instead:

$ printf "$(free -m | awk '/^Mem/{print $3}')"
5623$

Process substitution is supported by bash, zsh, Ksh88, ksh93, but not pdksh, mksh, or dash. The pipeline approach should be supported by all POSIX shells.