0

i have a question about how to store the output into variable and then later pipeline into another command

var=$(ps -auxc | grep -vE '^USER'  )

#get top CPU 
echo $var |  sort -nr -k3 | head -1  
#get top memory
echo $var | sort -nr -k4 | head -1
1
  • 1
    What's the question here? Commented Jul 9, 2014 at 17:55

2 Answers 2

1

Make sure to use quotes in assignment and while accessing variable:

var="$(ps -auxc | grep -vE '^USER')"

#get top CPU 
sort -nr -k3 <<< "$var" | head -1  
#get top memory
sort -nr -k4 <<< "$var" | head -1
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think using "" on assignments would give a difference. For the answer however, it's quite enough if the user is not too sensitive about the last newline as $() always chops it out.
@konsolebox: Yes that's right, while assigning "" may not be necessary.
@user3821571: Consider accepting any of the answers your liked here.
0

I'm not sure if this would always work:

IFS= read -rd '' var < <(ps -auxc | grep -vE '^USER')  ## -d '' may be -d $'\0'
echo -n "$var" | sort -nr -k3 | head -1  

However using readarray could:

readarray -t var < <(ps -auxc | grep -vE '^USER')
printf '%s\n' "${var[@]}" | sort -nr -k4 | head -1

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.