Bash – How to get the value of a named option of an already running process in Linux

argumentsbashprocessshell-script

I run the following command.

ps -e -o args | grep destiny | grep UNIX

I receive the following output.

/path/to/destiny -r -m UNIX -t TCP -p 1501

What command can I use the get the value of the printed arguments (for example -m or -t or -p)? I would like to achieve the following.

ps -e -o args | grep destiny | grep UNIX | <someCommand> -p this should print 1501

ps -e -o args | grep destiny | grep UNIX | <someCommand> -m this should print UNIX

ps -e -o args | grep destiny | grep UNIX | <someCommand> -t this should print TCP

Please note that -p, -m or -t may switch columns so printing with awk and choosing column by number is not an option.

Some more facts so that the parsing gets easier (I know it's possible I just lack the tooling knowledge).

  • if an option is not present an empty string will be returned
  • options that will be parsed will always have an argument/a value in this particular case

Best Answer

How about using sed:

ps -e -o args | grep -e 'destiny.*UNIX' | sed -e 's/.*-t\s\([A-Z0-9]*\).*/\1/'
ps -e -o args | grep -e 'destiny.*UNIX' | sed -e 's/.*-p\s\([A-Z0-9]*\).*/\1/'
ps -e -o args | grep -e 'destiny.*UNIX' | sed -e 's/.*-m\s\([A-Z0-9]*\).*/\1/'

sed -e 's/.*-t\s\([A-Z0-9]*\).*/\1/'

  • s/search for/replace with/options
  • s is to search.
  • .* matches any/all character(s) until we get to the "-t".
  • \s matches any whitespace.
  • ( begins a capture.
  • [A-Z0-9]* matches any capital letter and any number of any length.
  • ) ends the capture.
  • .* matches the remainder of the characters in the line (if there are any).
  • \1 replaces everything with the capture.
Related Question