Skip to content

Instantly share code, notes, and snippets.

@marjamis
Created August 24, 2020 06:37
Show Gist options
  • Save marjamis/693ce2735c242dac553e47272370ccf7 to your computer and use it in GitHub Desktop.
Save marjamis/693ce2735c242dac553e47272370ccf7 to your computer and use it in GitHub Desktop.
A probably overly complicated way to have multiple shells at the same time access a file, locked for sequential access, in which each shell would receive one line from that file. An example use-case is having 5 shells that are controlled at once to connect to 5 different ips in a file with the one command, this will output a different ip per she…
#!/bin/bash
FILE="ipsToConnectTo"
lineContents() {
# Checks if a line has a * pointer next to it to denote which is the next line that should be returned.
LN=$(grep --color=never -n \* $FILE | cut -f1 -d\:)
# If there is no * pointer it needs a manual reset to the right starting location. A precaution for how I used it but easily customisable.
if [ "${LN}" == "" ] ; then
echo '$LN isnt set reset the file'
exit 1
fi
# Current line with the * pointer.
IP=$(grep --color=never \* $FILE | cut -f1 -d\*)
echo $IP
# Set the next line to have the * pointer.
sed -ie $(expr $LN + 1)'s/$/*&/' $FILE
# Remove the current lines * pointer.
sed -ie $LN's:\*::g' $FILE
}
# The below lock system has been adapted from: https://blog.famzah.net/2013/07/31/using-flock-in-bash-without-invoking-a-subshell/
# Used for sequential access from the shells calling the script.
exec {lock_fd}>/tmp/linegrabber || exit 1
flock -w 3 "$lock_fd" || { echo "ERROR: flock() failed." >&2; exit 1; }
# Runs my function, the point of the script.
lineContents
# Unlock file. Unneeded as it's at the end and the process dying will release the lock but a precaution.
flock -u "$lock_fd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment