-1

I am trying create top command by myself. I stucked at point where i read list of running processes

IFS=$'\n'

p=$(ps -A -o %cpu  -o vsz -o time -o %c  --sort -%cpu | head -3  )

for i in $p
do
    echo $i
done;

But when I try echo lines for some reason all "n" is replaced by "\n"

%CPU    VSZ     TIME COMMAND
16.3 9761940 04:06:02 firefox
9.2 3255916 02:19:27 Web Co
te
t
^C

I would appreciate any help

Thank you

  • The script runs fine on [rextester.com](http://rextester.com/l/bash_online_compiler), and no 'n' are substituted with newlines. – KamilCuk Jun 03 '18 at 11:03
  • I guess the problem is leading ```$``` after ```=``` in ```IFS=$'\n'```. It is the same as saying set ```IFS``` to the value of variable ```$\n```, which leads to an empty value in most cases. – accdias Jun 03 '18 at 13:10
  • The problem is the separator used in ```IFS```. I've tested here setting ```IFS='^M'``` (That is ```CTRL+v``` followed by ```CTRL+M``` in vim) and it worked as you expected it to be. – accdias Jun 03 '18 at 13:31
  • This seems to work as well: ```IFS=$(printf "\n")```. – accdias Jun 03 '18 at 13:39
  • @accdias The syntax is correct, if the OP is actually using `bash`. In shells that don't support that kind of quoting, it's not a parameter expansion at all, so the `$` is treated literally. See my answer. – chepner Jun 03 '18 at 13:51
  • Thank you for help, when I quoted "$i" in echo, everything start working as should – Roman Válek Jun 03 '18 at 14:25
  • @chepner, thanks for the explanation. I didn't know that. – accdias Jun 03 '18 at 14:47

1 Answers1

1

You aren't running your script with bash, so your IFS is being set to three separate characters, rather than a single newline. One of those characters is n, so the unquoted expansion of p treats the letter n as a field separator.

Here's a simple example in dash:

$ IFS=$'\n'
$ printf '%s' "$IFS" | hexdump -C
00000000  24 5c 6e                                          |$\n|
00000003

The same example in bash:

$ IFS=$'\n'
$ printf '%s' "$IFS" | hexdump -C
00000000  0a                                                |.|
00000001
chepner
  • 497,756
  • 71
  • 530
  • 681