-1

I'm trying to add the following to my .bashrc:

cpu_info() {
    top -b -n1 | grep Cpu(s) | awk '{print $2 + $4}'
}

but bash is telling me:

bash: .bashrc: line 131: syntax error near unexpected token `('
bash: .bashrc: line 131: `  top -b -n1 | grep Cpu(s) | awk '{print $2 + $4}''

the command works fine in the terminal, not sure why its breaking in my bash script

any ideas?

3
  • 1
    how exactly does it work in the terminal?
    – ilkkachu
    Commented May 10 at 18:11
  • Regarding "the command works fine in the terminal" - no, it definitely would not. shellcheck.net finds more error in it than there are lines of code.
    – Ed Morton
    Commented May 10 at 21:57
  • As well as shellcheck does point out the unquoted ( 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 the s, and also isn't what you want).
    – ilkkachu
    Commented May 11 at 10:33

1 Answer 1

6

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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .