6

I am writing a bash script that creates 5 files with the extension ".P" and write a line of "something" into them. "P" represents a number and it's the PID of the process that creates the file. How can you do that? I am creating my file and writing into it like this: echo "something" > file_name

2 Answers 2

7

If you want to know the PID of the currently running bash session (which may very well be the one running your shell script and nothing else), you can use either $$ or ${BASHPID}. They are similar but subtly different; quoting the GNU bash 4.2 man page, "Shell variables" section:

BASHPID

Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized.

You may also find ${PPID} helpful; it holds the process ID of the parent process of the current bash session. If you want to go any further than that, you'll have to write some code to walk the process tree, and that will almost certainly be OS-dependent.

Try echo "something" > file_name.$$ in your shell for an example. And if you are doing anything serious, please always quote anything involving environment variables that you didn't set to a known safe value yourself.

If what you want is the PID of the process that originally created a file, as indicated in the title, I doubt that's possible (although it would depend on exactly which OS you're running). It just wouldn't be a useful piece of information to store in the general case, as PIDs are both reused as well as normally more or less random. On a busy multi-user system, they for all intents and purposes will be random for any given user.

0

Try this script

#!/bin/sh
for i in `seq 5`
do
    pid_var=`grep ^Pid: /proc/self/status | awk '{print $2}'`
    echo "something $$" > /tmp/filename$i.$pid_var
done

It's output will be something like this:

filename1.1234
filename2.1235
filename3.1236
filename4.1237
filename5.1238
2
  • Pointless use of grep and invoking awk. Wow. While this might work for illustration (on Linux; I don't know how many other OSes have a /proc, let alone /proc/self/status with the same format), you'd be a lot better off not using both grep and awk at least. For a start, try pid_var=$(awk '/^Pid:/ { print $2 }' /proc/self/status) instead. Starting awk is a fairly heavy operation; I learned this from experience myself piping through awk to do some string manipulation very much like this inside a tight shell script loop. There are often better ways. Commented Nov 25, 2013 at 8:39
  • Surely their must be BETTER ways. Thanks for pointing out. I was just demonstrating here that whatever questioner is looking for is possible. Script optimization was not considered here Commented Nov 25, 2013 at 9:25

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.