2

I want to redirect the output of this command firefox &. I know that adding & means that we will run the command in background and when we use it we receive [number of process in background] [PID]. This is what I have done:

firefox & > firefoxFile 

But when I open firefoxFile, I found it empty. I don't find [number of process in forground] [PID].

Yassel
  • 23

3 Answers3

3

In your comments you write that

I want to find the pid and the number of process in background

What about this

firefox &
pid=$!

echo "The PID for the background process is $pid" >&2

Having got the PID you can of course write its value to any file you choose.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
2

If your shell is bash[1], you can try:

exec 3>&2 2>firefoxFile; firefox & exec 2>&3-

It's your shell (eg. bash) which prints that [jobnum] pid background job notification to stderr, not firefox. This kludge temporarily redirects the stderr to the firefoxFile file, capturing into it that notification and whatever firefox will write to stderr during its lifetime.

It will NOT capture the [jobnum] Done firefox bash will print when the background job has terminated.


Your firefox & > file will be parsed as two commands 1. firefox & (which will run firefox in the background) and 2. > file (which will truncate file without writing anything to it). That's most certainly not what you intended.

[1] you can read here why this trick doesn't work in other shells; while it's possible to redirect the stderr in zsh, zsh does not write its prompts and job notifications to stderr, but to another fd pointing to the current terminal, opened especially for this purpose.

  • i try exec 3>&2 2>firefoxFile; firefox & exec 2>&3- and it works ,thank you so much, when we use exec the output of command is written to file instead of my terminal ? and what's the role of 3> ? the commande is working but i didn't understand it clearly – Yassel Feb 29 '20 at 20:57
  • 1
    When exec is used without any command, it just performs the redirections in the current shell. exec 3>&2 saves the old fd 2 (stderr) into fd 3. exec 2>&3- is a shortcut for exec 2>&3 3>&- ie it first restore 2 (stderr) from fd 3 where it was saved, and then close fd 3. –  Feb 29 '20 at 21:02
0

This is not exact, but close. You will just have to add a bit of sed.

firefox &
jobs -l | grep -E "\[[0-9]+\]\+" > firefoxFile