0

I am making a script as a sudo user that sends me CPU usage for my server, and mails me with the result of another script,

sudo sh -c '{
x=`ps aux | sort -nrk 3,3 | tr -s " " | cut -d" " -f 3,11- |awk '\'BEGIN { OFS = " " } { $1 = $1"%"; print }'\'`
/opt/fetch_script.sh $x
}| mailx mymail@mymail.com'

But it still gives me error cause of the AWK usage:

awk: 0: unexpected character '\'
aux: -c: line 1: syntax error: unexpected end of file

Any help please?

  • It's probably your nested quotes. What exactly are you trying to do? You should be able to get specific ps fields without all that extra processing e.g. ps axo pcpu= o comm= or ps -e -o pcpu= o comm= – steeldriver Nov 20 '16 at 15:45
  • I am building up script, that should print out the top 5 process that consumes the cpu, that printing the "cpu and process_name" columns only, to be like "5% /usr/sbin/apache2 -k start", thats the output that i wish for. – MohammedSimba Nov 20 '16 at 15:55
  • The script should be run for remote servers, so i run it under as sudo user, – MohammedSimba Nov 20 '16 at 15:57
  • 1
    You could try something like sh -c '/opt/fetch_script.sh "$(ps axo pcpu= o comm= | awk '\''{$1=$1"%"; print}'\'')"' – steeldriver Nov 20 '16 at 16:17
  • Worked like a charm :), thanks alot, please post your answer, – MohammedSimba Nov 20 '16 at 16:31
2

The issue is likely your attempt to nest quotes, however you are over-complicating things by not making use of the ps command's output format options. A simpler version (with consistent quoting) might be

sh -c '/opt/fetch_script.sh "$(ps axo pcpu= o comm= | awk '\''{$1=$1"%"; print}'\'')"'

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.