tofu
tofu

Reputation: 125

Appending on a new line in Linux

So I am trying to write a script which stores the cmds of processes in /proc. This is my script:

 $ re='^[0-9]+$
 $ for i in `ls /proc`; do if [[ $i =~ $re ]] ; then cd /proc/$i;cat cmdline >> /home/nisarg/CMD;fi; done 

$ above is the shell prompt.

I first set up a regex re which is useful to check if subdirectory has a numeric name in /proc. Example 23331. I do this because there are several files and directories in /proc which are not of interest to me. I am only interested in the directories having numeric names, because they hold the process data. Then I iterate over /proc and if (using the regex) I find that a directory has a numeric name, I enter this directory (using cd) and append the value stored in file cmdline to a file named CMD in my home folder.

My problem is that when I open the CMD file in /home/nisarg, I find that all the cmds are stored in a single line. I always thought that >> appends to a new line. Is it not?

If not, is there any way I could store each of them on a new line?

Upvotes: 0

Views: 1522

Answers (1)

choroba
choroba

Reputation: 242008

>> just appends to a file, it does not add a newline. The problem is that cmdline doesn't end in newline. You can just add echo to add a newline:

(echo ; cat cmdline) >> /home/nisarg/CMD

It's simple to use bash and its extglob option, though:

#! /bin/bash
shopt -s extglob
for c in /proc/+([0-9])/cmdline ; do
    echo
    cat "$c"
done > ~/CMD

Upvotes: 2

Related Questions