Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Script: What does this mean? "done < /dev/null & disown"

Tags:

syntax

bash

Can you please explain exactly what the last line of this does, and why it is needed?

while true; do
    /usr/bin/ssh -R 55555:localhost:22 -i ~/.ssh/tunnel-id [email protected]
    sleep 1
done < /dev/null & disown

That is the entire script, and it's purpose is to create an SSH tunnel to a relay server. I'm new to Bash, but it looks like it will continually try to keep the connection alive, but I don't understand the syntax of the last line.

This script is part of a process to use SSH behind a firewall, or in my case a NAT: http://martin.piware.de/ssh/index.html

like image 281
drifter Avatar asked Dec 13 '10 05:12

drifter


People also ask

What does dev null mean in bash?

/dev/null in Linux is a null device file. This will discard anything written to it, and will return EOF on reading. This is a command-line hack that acts as a vacuum, that sucks anything thrown to it.

What does >/ dev null 2 >& 1 mean?

It means that stderr ( 2 - containing error messages from the executed command or script) is redirected ( >& ) to stdout ( 1 - the output of the command) and that the latter is being redirected to /dev/null (the null device). This way you can suppress all messages that might be issued by the executed command.

What does done mean in bash?

Correct; done ends a while-loop (or for-loop or similar). Here it show that done can take the data from a variable. No; the < $input (meaning < name.

What means 2 >/ dev null?

Whether you are a new Linux user or an experienced bash programmer, it is highly probable that you encountered the cryptic command 2>/dev/null. Although this command looks technically complex, its purpose is very simple. It refers to a null device that is used to suppress outputs of various commands.


2 Answers

The last line redirects /dev/null into the loop as input -- which immediately returns EOF -- and runs the process in the background. It then runs a command disown(1) in the foreground, which detaches the process, preventing HUP signals from stopping it (sort of like nohup does.). the effect is to make the loop into something like a daemon process.

The loop overall runs the ssh command once a second. The command is opening an ssh tunnel, connecting it locally to port 5555 and remotely to port 22 (ssh). If there is something there to connect, it does; otherwise the redirected EOF causes it to terminate. It then tries aagain a second later.

(Or so I believe, I haven't actually tried it.)

In bash, disown is a built-in; use help disown to see some details.

like image 199
Charlie Martin Avatar answered Oct 17 '22 00:10

Charlie Martin


The redirection of /dev/null into the while loop effectively closes its stdin which should be equivalent to exec <&-.

like image 30
Dennis Williamson Avatar answered Oct 16 '22 22:10

Dennis Williamson