Bash - mwicat/personal GitHub Wiki

TCP connection

Connect

exec 5<>/dev/tcp/server/port

Send

echo -e "GET / HTTP/1.1\r\nHost: yahoo.com\r\nContent-Length: 0\r\n\r" >&5

Receive

cat <&5

Close

exec 5>&-

Header

#!/bin/bash
set -Eeuo pipefail

Default value for variable

USE_PYSPARK=${USE_PYSPARK:-1}

Format time/date

date +"%m-%d-%y"

Get script directory

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Absolute path

readlink -f filename
realpath filename

User prompt

echo "About do something bad"
read -p "OK? (y/N): " -r
echo
if ! [ $REPLY =~ ^[Yy]$ ](/mwicat/personal/wiki/-$REPLY-=~-^[Yy]$-)
then
  exit 1
fi

Prompt

PS1='\D{%T} ${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

Print date

echo "$(date '+%Y-%m-%d %H:%M:%S')"

Date in filename

echo "filename_$(date +%d%m%y%H%M)"

Robust scripts

http://www.davidpashley.com/articles/writing-robust-shell-scripts.html

set nounset
set errexit

Share history

shopt -s histappend
export PROMPT_COMMAND="history -a"

Then for read:

history -n

Screen

termcapinfo xterm* ti@:te@
hardstatus alwayslastline "%{-b ck}%?%-Lw%?%{bg}%n*%f %t%?(%u)%?%{wk}%?%+Lw%? %= %{r} %H %{g} %D %d/%m/%Y %0c "
startup_message off

screen -t aptitude 0 sudo aptitude
screen 1 mc
screen -t shell 2 bash
screen -t htop 3 sudo htop
screen -t root 4 sudo mc
screen -t ipython 5 ipython
screen -t shell mc
screen -t shell mc

tools of trade column (bsdmainutils)

pretty-print text in fixed size columns fold

split text into lines of N characters split

split one file into many smaller chunks

Midnight commander

''C-'' directory hotlist

Options

logging=0
jump=

function show_usage() {
    echo "Usage: `basename $0` MYARG"
    echo "Example: `basename $0` myarg"
}


while getopts "lj:h" opt; do
    case "$opt" in
    l) logging=1 ;;
    j) jump="$OPTARG" ;;
    h) show_usage >&2; exit ;;
    esac
done

shift $((OPTIND-1))

if [ "$#" -ne 1 ]; then
    show_usage >&2; exit
fi