1

I am trying to automate the following commands in a batch script,
But not sure how to take the [process id] from the [proc_status] to the kill command?

I tried $(!!) and $(1) without success.

user1@dev_server_100:/path> ./proc_status
PROC_NAME up, process id = 16394
user1@dev_server_100:/path> kill -9 16394

1 Answer 1

3

The overall technique you want is called command-substitution. You can have cmd-sub using var=$(echo "something) ; echo $var, or you may find in legacy code where the $( and ) replaced on both sides with the back-tic character (var='echo "something"' (Bad formatting here, but S.O. uses backtics for its own purposes. I can't remember how I've made this look right in the past).

Here are several solutions:

pidToKill=$( ./proc_status | awk '{print $NF}' )
kill $pidToKill

This lets awk count the Number of Fields (NF) in the line. The $NF is read by awk as "the value of $6" (NF==6) in this case.

If the output of ./proc_status will never change, then you can use a smaller utility to capture the PID, i.e.

pidToKill=$( ./proc_status | cut -d " " -f 6 )

kill $pidToKill 

This cuts the 6th field of the output data.

Finally, you can use the shell parameter substitution features to accomplish the same,

pidToKill=$( ./proc_status)
kill ${pidToKill##* }

The ##* (A trailing space is needed) says, search the value of pidToKill for the up to the last space in the value, and delete everything from the front to that point.


You should research why it is a bad thing to use kill -9 unless absolutely necessary. (Not a good habit to get into. If you know for certain that for this case -9 is the only solution, then you might want to include a comment in your code about why you are using -9.)

Sign up to request clarification or add additional context in comments.

Comments

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.