What is the right way to redirect script output use ">" or ">>" ?

Which one of the following are more accurate and why?

nohup myScript.sh 1>nohup_$(date +%Y%m%d%H%M%S).out 2>&1 &
nohup myScript.sh 1>>nohup_$(date +%Y%m%d%H%M%S).out 2>&1 &
nohup myScript.sh >nohup_$(date +%Y%m%d%H%M%S).out 2>&1 &
nohup myScript.sh  >>nohup_$(date +%Y%m%d%H%M%S).out 2>&1 &

I would go with 2nd line, but I am not sure why others are not better!!

None of them is "wrong", they just do different things.

> creates a new file. If the file already exists, the old one is truncated.

>> appends an existing file (or creates a new file if there's nothing there).

The 1 and 2 are file descriptor numbers. If you don't give it a number, it assumes 1, for standard output.

Since this is generating output file dynamically, is it ever possible that, the output file will get overwritten by new output from a subshell or something coming from script !? will it be wise to use >> if such possibility exists for this case?

 myScript.sh >nohup_$(date +%Y%m%d%H%M%S).out

:confused: No. nohup / myscript.sh don't open the file -- your shell does, before anything else is even run. They just use the file you opened for them.

1 Like