Skip to content

Instantly share code, notes, and snippets.

@mcsf

mcsf/colors Secret

Last active January 27, 2019 17:16
Show Gist options
  • Save mcsf/9369e3eb5d4d945e0dcc98cc9d3ef88f to your computer and use it in GitHub Desktop.
Save mcsf/9369e3eb5d4d945e0dcc98cc9d3ef88f to your computer and use it in GitHub Desktop.
Source code for an exercise in Unix concepts. https://lamda.blog/2019/01/27/jobs-and-pipes/
# Export escape sequences for terminal colors.
# set colors with max compatibility
if tput setaf 1 &> /dev/null; then
tput sgr0
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BOLD=$(tput bold)
RESET=$(tput sgr0)
else
BLACK="\033[1;30m"
RED="\033[1;31m"
GREEN="\033[1;32m"
YELLOW="\033[1;33m"
BLUE="\033[1;34m"
MAGENTA="\033[1;35m"
CYAN="\033[1;36m"
WHITE="\033[1;37m"
BOLD=""
RESET="\033[m"
fi
# export environment variables
export BLACK
export RED
export GREEN
export YELLOW
export BLUE
export MAGENTA
export CYAN
export WHITE
export BOLD
export RESET
#!/bin/bash
PORT=$1
# Sleep for a couple of seconds
sleep_some() {
number=$RANDOM
let "number %= 2"
let "number += 1"
sleep $number
}
# Simulate server by "waiting" for incoming connections that randomly request
# one of three resources.
main() {
sleep_some
number=$RANDOM
let "number %= 4"
case $number in
0) echo "GET /index.html HTTP/1.1 (200)";;
1) echo "GET /foo HTTP/1.1 (404)";;
2) echo "GET /private HTTP/1.1 (403)";;
3) echo "FATAL ERROR. Terminating."; exit 1;;
esac
main
}
echo Listening on port ${PORT}…
main
#!/bin/bash
NAME=$1
COLOR=$2
while IFS='' read -r line || [[ -n "$line" ]]; do
echo -e "$COLOR[$NAME]: $RESET$line"
done
#!/bin/bash
# Ensure colour-coding variables are available
. ./colors
send() {
echo "$1" | ./namespace runner $RED
}
# Kill spawned jobs before exiting
trap 'send "Terminating…" && kill `jobs -p` 2>/dev/null' EXIT
send "Spawning fake servers…"
./listen 8000 | ./namespace web_01 $GREEN &
./listen 8001 | ./namespace web_02 $BLUE &
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment