2

I'm trying to execute a ps command for the servers which i'm taking it into an array and take the output of that command into a variable and then take the first line of the content again into a variable. Please find below my code.

#!/bin/bash
echo "enter the servers names..."
read -a array
for i in "${array[@]}"
do
content=`ps -auxwww | grep $i`
line=${head -1 content}
echo $line
done
exit 0

I'm unable to take the first line from the $content. Kindly help on how to extract the first line again into a variable and then display the first line fully. I don't want to create a new file to save the contents. I would like to do it in one go.

codeforester
  • 39,467
  • 16
  • 112
  • 140
sdgd
  • 723
  • 1
  • 17
  • 38
  • What is `${head -1 content}` supposed to be? `${}` is for wrapping around variables. If you want to get the output of a command, the syntax is `$(command)`. – Barmar Apr 29 '17 at 18:07

2 Answers2

1

You can directly take 1st line from the unix command itself

content=`ps -auxwww | grep $i | head -1`

Srihari Karanth
  • 2,067
  • 2
  • 24
  • 34
1

You can do it in one shot, this way:

line=$(ps -auxwww | grep -- "$i" | head -1)
  • it is better to use $() instead of back ticks
  • -- will prevent grep from failing in case any of your server names starts with a -
  • it is important to enclose $i in double quotes to prevent issues caused by word splitting and globbing (you can use shellcheck to catch such issues in your script)

If you really want to do it in two steps, then:

content=$(ps -auxwww | grep -- "$i")
line=$(head -1 <<< "$content")

See also:

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140