Running sudo in background

A common way of running bash commands in background is attaching “&” to the end of the command. But what happens if you need to run a sudo command in the background? Appending “&” to the end of “sudo whatever.sh &” will not work. According to this thread on SlackOverflow:

The problem is that the sudo command itself is being run in the background. As a result, it will be stopped (SIGSTOP) when it tries to access the standard input to read the password.

A simple solution is to create a shell script to run synaptic & and then sudo the script in the foreground (i.e. without &).

Yes, making a wrapper script that runs a sudo command and then calling this wrapper script with “&” at the end is a common way, but there is another alternative that I like (especially when you don’t really care about command output): use screen utility:

screen -d -m sudo whatever.sh

This will create a new detached screen session and run a sudo command inside of it without blocking the terminal (or program execution, if you run the command from some other script/program). If the command is long running, you will be able to attach screen and see output. When command completes execution, the screen session will be terminated.

Will leave it here for future reference.

TCP requests with plain bash in Linux

Recently I had a problem where I need to check if specific port of specific host was available before I can proceed further. Basically it was a docker composer running a container which depends on mysql service and I had to make sure mysql service was available before I can continue with my main docker container.

First I looked into nc implementation of a waiting part in the container entrypoint that looked something like this:

sh -c 'until nc -z mysql_host 3306; do sleep 1; done'

but it turned out I didn’t have nc installed in the container and was lazy enough to rebuild the whole thing just for this tiny tool.

Apparently, this discussion pointed out a solution:

sh -c 'until printf "" 2>>/dev/null >>/dev/tcp/mysql_hostname/3306; do sleep 1; done'

which was something I never saw before, so a bit of googling brought me to this nice page with an example how to make HTTP request and get response while working with /dev/tcp. Useful to know, so I am leaving it here.