It is not the awk
command causing issues, but the pattern you're using with grep
.
An unquoted parenthesis is special to the shell. It introduces a sub-shell, but in the context that you're using it, it makes no sense, hence the syntax error.
Therefore, the text Cpu(s)
must be quoted as 'Cpu(s)'
. If you intend for this to be a piece of literal string you want to search for, you should ideally also use grep
with its -F
option. This stops grep
from interpreting the pattern as a regular expression.
However, using grep
together with awk
is almost always unnecessary, as awk
is perfectly well equipped to do the same thing:
cpu_info () {
top -b -n 1 | awk '/Cpu\(s)/ { print $2 + $4 }'
}
Here, I escape the (
to interpret it as a literal left parenthesis and not as the start of a grouping of a sub-expression.
(
and helpfully asks if it was supposed to be quoted, the rest of the errors it shows are just a consequences of parsing going off due to the(
. But no, I don't see how that could work on the terminal either, that unquoted(
is an error in pretty much any shell (including tcsh), though in zsh it just makes that a glob (which probably doesn't match and isn't what you want), and in fish it makes it a command substitution (which probably gives an "unknown command" for thes
, and also isn't what you want).