2
#!/bin/bash
echo "Enter process name"
read process
if pgrep "$process" > /dev/null
then
    echo 0 $(awk '/Rss/ {print "+", $2}' /proc/`pidof $process`/smaps) | bc;
    echo "Kb"
else
    echo "Process $process not running"
fi

The output of the code above is

41250 
Kb

and I need the "Kb" output in the same line as the number like this

41250  Kb
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

3 Answers3

2

You can use echo -n to output data without a trailing newline but, for this particular case, awk is perfectly capable of doing arithmetic and formatting on its own, without involving bc or unnecessary sub-processes:

awk '/Rss/ {sum += $2} END {print sum" Kb"}' /proc/`pidof $process`/smaps

You can see that in the following transcript which adds up the two Rss figures 75 and 11 to get 86:

pax> printf Rss 75\nCss 22\nRss 11\n' | awk '/Rss/ {sum += $2} END {print sum" Kb"}'
86 Kb
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

Use the -n Flag.

Example:

echo -n 'I do not want a new line,'
echo ' because there is something else here.'

Use $ man echo to get more information.

0

The newline after 41250 was actually from bc, not echo.

Capturing output of bc in a variable removes trailing newlines (ref).

#!/bin/bash
kbCount=$( echo "1+2" | bc)
echo $kbCount "Kb"

Now you should be able to fix it :)

Jokester
  • 5,501
  • 3
  • 31
  • 39