Muneeb K
Muneeb K

Reputation: 487

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

Upvotes: 1

Views: 356

Answers (1)

John1024
John1024

Reputation: 113814

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.

Improvement

The above works as long as the output does not contain printf-active characters. It is much better practice to use an explicit format string and thereby avoid unpleasant surprises:

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

Upvotes: 2

Related Questions