0

I have a shell script that I'm writing to search for a process by name and return output if that process is over a given value.

I'm working on finding the named process first. The script currently looks like this:

#!/bin/bash

findProcessName=$1
findCpuMax=$2
#echo "parameter 1: $findProcessName, parameter2: $findCpuMax" 

tempFile=`mktemp /tmp/processsearch.XXXXXX`
#echo "tempDir: $tempFile"

processSnapshot=`ps aux > $tempFile`

findProcess=`awk -v pname="$findProcessName" '/pname/' $tempFile`
echo "process line: "$findProcess

`rm $tempFile`

The error is occuring when I try to pass the variable into the awk command. I checked my version of awk and it definitely does support the -v flag.

If I replace the '/pname/' portion of the findProcess variable assignment the script works.

I checked my syntax and it looks right. Could anyone point out where I'm going wrong?

1 Answer 1

2
  1. The processSnapshot will always be empty: the ps output is going to the file

  2. when you pass the pattern as a variable, use the pattern match operator:

    findProcess=$( awk -v pname="$findProcessName" '$0 ~ pname' $tempFile )
    
  3. only use backticks when you need the output of a command. This

    `rm $tempFile` 
    

    executes the rm command, returns the output back to the shell and, it the output is non-empty, the shell attempts to execute that output as a command.

    $ `echo foo`
    bash: foo: command not found
    $ `echo whoami`
    jackman
    

    Remove the backticks.

Of course, you don't need the temp file at all:

pgrep -fl $findProcessName
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Thank you. Also, thank you for explaining each part of what was wrong with the shell script and not just telling me "use pgrep". I'm still pretty green to shell scripting so it's ultra helpful to have each of those explained.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.