Sunday 1 October 2017

A nohup trick or two

We've all been frequent users of nohup throughout our system administrator careers. Today I'll share a trick or two about nohup which you may or may not already know.

I'll be using the below script as my command to run during the demonstrations.

root@sandbox:/# cat hup.bash
#!/bin/bash

while true

do
echo "printting endlessly"
date
sleep 5
done

It's a simple infinite while loop print the string "printing endlessly" and the date every 5 seconds.


Trick 1 - Redirect output of command to a file other than nohup.out:

When we run a command following the convention nohup command & the output of the command if any gets redirected to a file named nohup.out created in the directory from where the command was run. This is fine when running one command on one server but if we are running a command like this on multiple servers in a loop then we might need separate output files for each server.

To accomplish what I just mentioned you could use nohup as follows:

root@sandbox:/# nohup ./hup.bash &> $(hostname)_$(date '+%d-%m-%y').txt &
[1] 1131
root@sandbox:/# ls -l sandbox_01-10-17.txt
-rw-r--r--   1 root     root          98 Oct  1 21:05 sandbox_01-10-17.txt
root@sandbox:/# tail -5 !$
tail -5 sandbox_01-10-17.txt
Sun Oct  1 21:05:07 IST 2017
printting endlessly
Sun Oct  1 21:05:12 IST 2017
printting endlessly
Sun Oct  1 21:05:17 IST 2017

The output of the command run via nohup got redirected to the file name I porivded and not to nohup.out.


Trick 2 - Nohup an already running process:

For the second trick I'll demonstrate how we can use nohup on a process which is already running.

Let's run the hup.bash script again in the background.

root@sandbox:/# ./hup.bash &
printting endlessly
Sun Oct  1 21:08:31 IST 2017
[1] 1234
root@sandbox:/# printting endlessly
Sun Oct  1 21:08:36 IST 2017
printting endlessly
Sun Oct  1 21:08:41 IST 2017
printting endlessly
Sun Oct  1 21:08:46 IST 2017


Although I ran the script in the background the stdout is being redirected to the tereminal but notice it got frozen after a few runs. That is because I ran nohup on the process id in a separate terminal window as shown below:

root@sandbox:/# nohup -p 1234
Sending output to nohup.out
root@sandbox:/# tail nohup.out
printting endlessly
Sun Oct  1 21:07:50 IST 2017
printting endlessly
Sun Oct  1 21:07:55 IST 2017
printting endlessly
Sun Oct  1 21:08:00 IST 2017
printting endlessly
Sun Oct  1 21:08:51 IST 2017
printting endlessly
Sun Oct  1 21:08:56 IST 2017


The output of all subsequent iterations gets directed to nohup.out.


I hope you'll find these tricks useful and I thank you for reading.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...