# *** Dynamic serialization in bash ***
# The follwing example can keep track of PIDs of running background processes
# The interresting part is the loading and the storage (1. and 3.) !
# *** 1. Load PIDs ***
pidfile=/foo/bar
[[ -e $pidfile ]] && . $pidfile #Source the file !
# *** 2. Do the work ***
func1 () {
varname="$1pid"
mybin &
export ${varname}=$! # Pid of last background process
}
func2 () {
varname="$1pid"
[[ ${!varname} ]] && kill ${!varname}} || echo "Fuck"
unset ${varname}
}
if [[ $whatever ]]; then
func1 d
else
func2 d
fi
# *** 3. Store back PIDs ***
[[ -e $pidfile ]] && rm $pidfile # Clean out, only variables that are still set will be serialized
for var in "d" "t" "q"; do
varname="${var}pid"
if [[ ${!varname} ]]; then
declare -p ${varname} | cut -d ' ' -f 3- >> $pidfile # Here is the magic : "declare -p" handles the quotes for you :D
fi
done
bash
<iframe width="100%" height="848" src="http://ginkobox.fr/vamp/index.php?embed=54986909effb0" type="text/html"></iframe>
Text only - Permalink - Snippet public post date 22/12/2014
# Starts and kills SSH tunnels
# *** ssh command explained ***
# -S : The control socket, it's used to monitor the ssh connection
# -M : Mandatory for the use of -S (indicates that this connection is the master). If -M is not specified, ssh looks for the socket of the master connection to attach this ssh session as a slave.
# -N : Don't execute commande
# -f : Go to background (but allow ssh to ask for passwd, that's the difference from a shell &)
# -O : Command line for socket
# -L : Local port forwarding
connect () {
ssh -M -S ~/.tunnel_${2}.sock -f user@host -L $1 -N && echo "Tunnel $2 started successfully" || echo "Tunnel $2 failed to start"
}
disconnect () {
case $1 in
d|t|q) ssh -S ~/.tunnel_${1}.sock -O exit user@host;;
*) "Unknown target"; exit 1;;
esac
}
case $1 in
d) connect "<local_port_d>:target_d.tld:<remote_port_d>" "d";;
t) connect "<local_port_t>:target_t.tld:<remote_port_t>" "t";;
q) connect "<local_port_q>:target_q.tld:<remote_port_q>" "q";;
-k) disconnect $2;;
-h|--help) echo "tunnel.sh [-K] <target in [dtq]>"; exit 0;;
*) echo "Unknown target"; exit 1;;
esac
ssh tunnel bash
<iframe width="100%" height="722" src="http://ginkobox.fr/vamp/index.php?embed=54985416ccf48" type="text/html"></iframe>
Text only - Permalink - Snippet public post date 22/12/2014