# bashclip Bash clipboard of snippets # Merge Lines 2-by-2 ```bash sed '$!N;s/\n/ /' infile ``` # Temporary files ```bash BASE=$(basename $0 .sh) TEMPHTML="$BASE.html" TEMPTXT="$BASE.txt" TEMPJSON="$BASE.json" TEMPCOOKIE="$BASE.cookie" TEMPCSV="$BASE.csv" ``` # Clean Exit ```bash function clean_temp_files() { rm -f $TEMPHTML $TEMPJSON $TEMPCOOKIE $TEMPCSV } trap clean_temp_files EXIT ``` # Die ```bash function die() { RETCODE=$1 if [ "" == "$1" ] then RETCODE=255 fi echo " FAILED" exit $RETCODE } ``` # Minimal RC Management ```bash RCFILE="$HOME/.rcfile" function readrc() { echo "+- Reading credentials from $RCFILE" USER=$(grep "user=" $RCFILE | awk -F'=' '{print $2}') PASSWD=$(grep "password=" $RCFILE | awk -F'=' '{print $2}') } if [ ! -e $RCFILE ] then echo "+- Credentials file does not exist" read -e -p " +- Username : " TEMP USER=$TEMP TEMP="" read -e -s -p " +- Password : " TEMP PASSWD=$TEMP # Make the file unreadable by others *BEFORE* putting password. touch $RCFILE chmod go-r $RCFILE echo "user=$USER">$RCFILE echo "password=$PASSWD" >> $RCFILE echo "" else readrc fi ``` # Logging ```bash LOG_ENABLED=1 LOGFILE="/to.log" function log() { if [ 1 -eq $LOG_ENABLED ] then DATELOG=$(date) echo -e "$@" echo -e "$DATELOG $(hostname) $(basename $0): $@" >> $LOGFILE fi } DATE_START_ALL=$(date +%s) log "############################################################" log "Started @ $DATE_START_ALL" ``` # URLencode ```bash rawurlencode() { local string="${1}" local strlen=${#string} local encoded="" local pos c o for (( pos=0 ; pos local url_encoded="${1//+/ }" printf '%b' "${url_encoded//%/\\x}" } ``` # Zeroing a file ```bash : > filename ``` # List of Opened Socket without netstat ```bash lsof -i4 -n ``` # Colors in scripts use with **echo -e** ```bash GREEN="\\033[1;32m" RED="\\033[1;31m" MAGENTA="\\033[1;35m" BLUE="\\033[1;34m" WHITE="\\033[0;02m" LIGHTGREY="\\033[1;08m" YELLOW="\\033[1;33m" CYAN="\\033[1;36m" NORMAL="\\033[0;39m" ``` # Replace a key=value in a file With **infile** being: ```ini [section] key=value key2=value2 ``` ``` sed -i "s/key=.*/key=NEW/" infile ``` In a section ``` sed -i '/^\[section\]/{$!{N;s/key=.*/key=NewMULTILINE/;ty;P;P;:y}}' infile ``` # Extract value from an ini file Warning: iworks only for first key after [section] ``` sed -nr '/\[section\]/ { :l /^[ |\t]*key[ |\t]*=/ { s/.*=[ ]*//; p; q;}; n; b l;}' ``` # Match several times the same key=value ```bash awk 'match($0, /ID>(TWA[^ ]+AS)<\/ID>/, asid){if(match($0, /Strategy="([^ ]+)">/, strategy)){print asid[1], strategy[1]}}' *.AS ``` OR ```bash grep -Pio 'Strategy="\K[^"]*' ``` # Network interface details ## MAC Address ```bash cat /sys/class/net/eth0/address ``` ## Link status - Integer ```bash cat /sys/class/net/eth0/carrier ``` - String ```bash cat /sys/class/net/eth0/operstate ```