49

Can anyone help me out with this problem?

I'm trying to save the awk output into a variable.

variable = `ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}'`
printf "$variable"

EDIT: $12 corresponds to a parameter running on that process.

Thanks!

Noam M
  • 3,156
  • 5
  • 26
  • 41
Jeremy
  • 791
  • 2
  • 7
  • 11
  • The problem is not really clear. What is the error you get? What is the line from `ps -ef` and what do you expect in $variable ? (if you can not provide real data, then generate a sanitized example that shows the problem instead.) – NiKiZe Sep 06 '13 at 01:35
  • Problem: variable does not show up in the printf statement. End goal: $12 corresponds to a serial number that is running with that process. I want to save that parameter into a variable so I can work with it. – Jeremy Sep 06 '13 at 02:39

4 Answers4

67
#!/bin/bash

variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'`
echo $variable

Notice that there's no space after the equal sign.

You can also use $() which allows nesting and is readable.

vvns
  • 3,548
  • 3
  • 41
  • 57
24

I think the $() syntax is easier to read...

variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')

But the real issue is probably that $12 should not be qouted with ""

Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef is and what is expected in variable.

NiKiZe
  • 1,256
  • 10
  • 26
  • 2
    There's supposed to be an `awk` after the last pipe and before the `'{printf`. It was probably accidentally removed when the answer was edited. – aDroid Jan 27 '17 at 22:02
3

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

0
variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')

The [p] is a neat trick to remove the search from showing from ps

@Jeremy If you post the output of ps -ef | grep "port 10", and what you need from the line, it would be more easy to help you getting correct syntax

Jotne
  • 40,548
  • 12
  • 51
  • 55