Muneeb K Muneeb K - 10 months ago 43
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. command substitution: line 23: syntax error near unexpected token `(' command substitution: line 23: `awk '/^Mem/ {print $3}' <(free -m))"'


Let's run the line in question under bash:

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

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}')"

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.