1

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))"'
1
  • check awk is available by running this in your cli . awk 'BEGIN{ print 1}' Commented Jun 4, 2016 at 6:42

1 Answer 1

2

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}')"
Sign up to request clarification or add additional context in comments.

1 Comment

@EdMorton Very true. Added to answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.