#------------------------------------------------------------- # Archiving functions. #------------------------------------------------------------- # Creates an archive. archive() { if [ "$#" -ne 0 ] ; then FILE="$1" case "$FILE" in *.tar.bz2|*.tbz2) shift && tar cvjf "$FILE" $* ;; *.tar.gz|*.tgz) shift && tar cvzf "$FILE" $* ;; *.tar) shift && tar cvf "$FILE" $* ;; *.rar) shift && rar "$FILE" $* ;; *.zip) shift && zip "$FILE" $* ;; *.7z) shift && 7zr a "$FILE" $* ;; *) echo "'$1' cannot be archived via archive()" ;; esac else echo "usage: archive [file] [contents]" fi } # Extract an archive of any type. extract() { local opt local OPTIND=1 while getopts "hv?" opt; do case "$opt" in h) cat < options: -h show this message and exit -v verbosely list files processed End-Of-Usage return ;; v) local -r verbose='v' ;; ?) extract -h >&2 return 1 ;; ac done shift $((OPTIND-1)) [ $# -eq 0 ] && extract -h && return 1 while [ $# -gt 0 ]; do if [ -f "$1" ]; then case "$1" in *.tar.bz2|*.tbz|*.tbz2) tar "xvjf" "$1" ;; *.tar.gz|*.tgz) tar "xvzf" "$1" ;; *.tar.xz) xz --decompress "$1"; set -- "$@" "${1:0:-3}" ;; *.tar.Z) uncompress "$1"; set -- "$@" "${1:0:-2}" ;; *.bz2) bunzip2 "$1" ;; *.deb) dpkg-deb -xv "$1" "${1:0:-4}" ;; # *.deb) sudo dpkg -i $1 ;; *.exe) cabextract "$1" ;; *.pax.gz) gunzip "$1"; set -- "$@" "${1:0:-3}" ;; *.gz) gunzip "$1" ;; *.lzma) unlzma "$1" ;; *.pax) pax -r -f "$1" ;; *.pkg) pkgutil --expand "$1" "${1:0:-4}" ;; *.rar) unrar x "$1" ;; *.rpm) rpm2cpio "$1" | cpio -idmv ;; # *.rpm) sudo alien -dik $1;; *.tar) tar "xvf" "$1" ;; *.txz) mv "$1" "${1:0:-4}.tar.xz"; set -- "$@" "${1:0:-4}.tar.xz" ;; *.xz) xz --decompress "$1" ;; *.zip|*.war|*.jar) unzip "$1" ;; *.Z) uncompress "$1" ;; *.7z) 7za x "$1" ;; *) echo "'$1' cannot be extracted via extract" >&2;; esac else echo "extract: '$1' is not a valid file" >&2 fi shift done } # ls archives (inspired by `extract`) lsz() { if [ $# -ne 1 ] then echo "lsz filename.[tar,tgz,gz,rar,zip,etc]" return 1 fi if [ -f $1 ] ; then case $1 in *.tar.bz2|*.tar.gz|*.tar|*.tbz2|*.tgz) tar tvf $1;; *.rar) unrar l $1;; *.zip) unzip -l $1;; *) echo "'$1' unrecognized." ;; esac else echo "'$1' is not a valid file" fi } # Creates an archive (*.tar.gz) from given directory. maketar() { tar cvzf "${1%%/}.tar.gz" "${1%%/}/"; } # Create a ZIP archive of a file or folder. makezip() { zip -r "${1%%/}.zip" "$1" ; } #------------------------------------------------------------- # Calculator functions. #------------------------------------------------------------- # Calculate an expression e.g. calc 1+1. calc() { echo "$@"|bc -l; } #------------------------------------------------------------- # cd. #------------------------------------------------------------- # cd = pushd, b = go backwards (popd), f = go forwards (kind of like "unpopd"). #alias d='dirs' #alias b='pushd +1' #alias f='pushd -0' cd() { if [ "$*" = "" ]; then pushd $HOME >/dev/null else pushd "$*" >/dev/null fi } # cd to the directory a symbolically linked file is in. cdlink { if [ "x$1" = "x" ] ; then echo "Missing Arg" elif [ -L "$1" ] ; then link=`/bin/ls -l $1 | tr -s ' ' | cut -d' ' -f10` if [ "x$link" = "x" ] ; then echo "Failed to get link" return fi dirName_=`dirname $link` cd "$dirName_" else echo "$1 is not a symbolic link" fi return } # cd to the dir that a file is found in. cdff { filename=`find . -name $1 | grep -iv "Permission Denied" | head -1` if [ "xx${filename}xx" != "xxxx" ] ; then dirname=${filename%/*} if [ -d $dirname ] ; then cd $dirname fi fi } #------------------------------------------------------------- # Directory functions. #------------------------------------------------------------- # Jumps to a directory at any level below using globstar. jd() { if [ -z $1 ]; then echo "Usage: jd [directory]"; return 1 else cd **/$@ fi } # Go up a specified number of directories. # If you pass no arguments, it just goes up one directory. # If you pass a numeric argument it will go up that number of directories. # If you pass a string argument, it will look for a parent directory with that name and go up to it. up() { dir="" if [ -z "$1" ]; then dir=.. elif [[ $1 =~ ^[0-9]+$ ]]; then x=0 while [ $x -lt ${1:-1} ]; do dir=${dir}../ x=$(($x+1)) done else dir=${PWD%/$1/*}/$1 fi cd "$dir"; } #------------------------------------------------------------- # Disk functions. #------------------------------------------------------------- # Pretty-print of 'df' output. # Inspired by 'dfc' utility. mydf() { for fs ; do if [ ! -d $fs ] then echo -e $fs" :No such file or directory" ; continue fi local info=( $(command df -P $fs | awk 'END{ print $2,$3,$5 }') ) local free=( $(command df -Pkh $fs | awk 'END{ print $4 }') ) local nbstars=$(( 20 * ${info[1]} / ${info[0]} )) local out="[" for ((j=0;j<20;j++)); do if [ ${j} -lt ${nbstars} ]; then out=$out"*" else out=$out"-" fi done out=${info[2]}" "$out"] ("$free" free on "$fs")" echo -e $out done } #------------------------------------------------------------- # Downloading functions. #------------------------------------------------------------- # More persistent wget for fetching files to a specific filename. wgettofile() { [ $# -ne 2 ] && echo "usage: wgettofile " && return 1 urltofetch=$1 fname="$2" wget -O "$fname" $urltofetch } #------------------------------------------------------------- # Email functions. #------------------------------------------------------------- # Email me a short note. emailme() { if [ $# -eq 0 ] then echo Usage: emailme text return 1 fi echo "$*" | mailx -s "$*" administrator echo "Sent email" } #------------------------------------------------------------- # File functions. #------------------------------------------------------------- # Backup file(s) filebackup() { if [ $# -lt 1 ] then echo Please supply a file to backup return 1 fi date=`date +%Y%m%d-%H%M%S` for i in "$@" do echo Backed up $i to $i.$date cp "$i" "$i".$date done } # Output a text file with line numbers # # Overriding the newline-to-tab conversion (with the -d flag) and # replacing newlines with TAB-newline, maintaining the newline # but indenting it. sed = will number the lines in the output, # and the -s switch on paste will restore our whitespace keeping # the line number justified to the left. filecatno() { if [ $# == 0 ]; then echo "No filename provided." else sed = "$1" | paste -s -d '\t\n' - - fi } # Show all strings (ASCII & Unicode) in a file. filecatstr() { cat "$1" | tr -d "\0" | strings ; } # Changes the extension of all of the specified files in a directory. # It takes two arguments, first the original extension, # then the extension to replace it with. # For example # filechgext html php filechgext() { for file in *.$1 ; do mv "$file" "${file%.$1}.$2" ; done } # Find a file with pattern $1 in name and Execute $2 on it: fileexec() { find . -type f -iname '*'"${1:-}"'*' \ -exec ${2:-file} {} \; ; } # Fast find, using globstar. filefind() { ls -ltr **/$@ } # Swap 2 filenames around, if they exist. fileswap() { local TMPFILE=tmp.$$ [ $# -ne 2 ] && echo "Usage: fileswap file1 file2" && return 1 # [ $# -ne 2 ] && echo "fileswap: 2 arguments needed" && return 1 [ ! -e $1 ] && echo "fileswap: $1 does not exist" && return 1 [ ! -e $2 ] && echo "fileswap: $2 does not exist" && return 1 mv "$1" $TMPFILE mv "$2" "$1" mv $TMPFILE "$2" } # Moves file to ~/.Trash (use instead of rm). filetrash() { if [ $# -eq 0 ] then echo Usage: filetrash FILE... return 1 fi local DATE=$(date +%Y%m%d) [ -d "${HOME}/.Trash/${DATE}" ] || mkdir -p ${HOME}/.Trash/${DATE} for FILE in "$@" do mv "${FILE}" "${HOME}/.Trash/${DATE}" echo "${FILE} trashed!" done } # Overwrite a file with zeroes - http://www.shell-fu.org/lister.php?id=94 filezero() { case "$1" in "") echo "Usage: filezero " return -1; esac filesize=`wc -c "$1" | awk '{print $1}'` dd if=/dev/zero of=$1 count=$filesize bs=1 } #------------------------------------------------------------- # Firewall functions. #------------------------------------------------------------- # Ban IP ban() { if [ "`id -u`" == "0" ] ; then iptables -A INPUT -s $1 -j DROP else sudo iptables -A INPUT -s $1 -j DROP fi } #------------------------------------------------------------- # Grep Find Search functions. #------------------------------------------------------------- # Find a file with a pattern in name: # Examples: # ff ash ff() { find . -type f -iname '*'"$*"'*' -ls ; } # Find a file whose name starts with a given string. ffs() { /usr/bin/find . -name "$@"'*' ; } # Find a file whose name ends with a given string. ffe() { /usr/bin/find . -name '*'"$@" ; } # Find files larger than a certain size (in bytes). ffbigger() { find . -type f 2>/dev/null | xargs \du -a -b 2>/dev/null | awk "{ if ( \$1 > $@) print \$0 }" | sort -hr; } # Find a pattern in a set of files and highlight them: #+ (needs a recent version of egrep). findstr() { OPTIND=1 local mycase="" local usage="findstr: find string in files. Usage: grepstr [-i] \"pattern\" [\"filename pattern\"] " while getopts :it opt do case "$opt" in i) mycase="-i " ;; *) echo "$usage"; return ;; esac done shift $(( $OPTIND - 1 )) if [ "$#" -lt 1 ]; then echo "$usage" return; fi find . -type f -name "${2:-*}" -print0 | \ xargs -0 egrep --color=always -sn ${case} "$1" 2>&- | more } # Search for a word in the Unix word list. word() { /bin/grep ^"$@"$ /usr/share/dict/words ; } # Search for a word in the Unix word list that ends with the chars. wordstarts() { /bin/grep ^"$@" /usr/share/dict/words ; } # Search for a word in the Unix word list that ends with the chars. wordends() { /bin/grep "$@"$ /usr/share/dict/words ; } #------------------------------------------------------------- # Info functions. #------------------------------------------------------------- # Get current host related info. ii() { echo -e "\nYou are logged on ${BRed}$HOST" echo -e "\n${BRed}Additionnal information:$NC " ; uname -a echo -e "\n${BRed}Users logged on:$NC " ; w -hs | cut -d " " -f1 | sort | uniq echo -e "\n${BRed}Current date :$NC " ; date echo -e "\n${BRed}Machine stats :$NC " ; uptime echo -e "\n${BRed}Memory stats :$NC " ; free echo -e "\n${BRed}Diskspace :$NC " ; mydf / $HOME echo -e "\n${BRed}Local IP Address :$NC" ; my_ip echo -e "\n${BRed}Open connections :$NC "; netstat -pan --inet; echo } #------------------------------------------------------------- # Misc functions. #------------------------------------------------------------- # Waits for the user to press a y or n. # # Example: # if ask "Kill process $pid <$pname> with signal $sig?" # then kill $sig $pid # fi ask() { echo -n "$@" '[y/n] ' ; read ans case "$ans" in y*|Y*) return 0 ;; *) return 1 ;; esac } # Repeat n times command. # # Example: # repeat 10 ls repeat() { local i max max=$1; shift; for ((i=1; i <= max ; i++)); do # --> C-like syntax eval "$@"; done } # Do something very quietly. runquiet() { ( $@ ) >/dev/null 2>/dev/null } #------------------------------------------------------------- # Network functions. #------------------------------------------------------------- # myIP address ipall() { ifconfig lo | grep 'inet ' | sed -e 's/:/ /' | awk '{print "lo: " $2 " " $3 " " $4 " " $5 " " $6}' ifconfig em1 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "em1 (IPv4): " $2 " " $3 " " $4 " " $5 " " $6}' ifconfig em1 | grep 'inet6 ' | sed -e 's/ / /' | awk '{print "em1 (IPv6): " $2 " " $3 " " $4 " " $5 " " $6}' ifconfig em2 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "em2 (IPv4): " $2 " " $3 " " $4 " " $5 " " $6}' ifconfig em2 | grep 'inet6 ' | sed -e 's/ / /' | awk '{print "em2 (IPv6): " $2 " " $3 " " $4 " " $5 " " $6}' } # Get IP adress on ethernet. myip() { MY_IP=$(/sbin/ifconfig em1 | awk '/inet/ { print $2 } ' | sed -e s/addr://) echo ${MY_IP:-"Not connected"} } getip() { for each in $@; do echo $each echo "nslookup:" nslookup $each | grep Address: | grep -v '#' | egrep -o '([0-9]+\.){3}[0-9]+' echo "ping:" ping -c1 -t1 $each | egrep -o '([0-9]+\.){3}[0-9]+' | head -n1 done } #------------------------------------------------------------- # Process functions. #------------------------------------------------------------- psnice() { if ! [ -z "$1" ] then # Take a parameter pid. ionice -c3 -p$1 ; renice -n 19 -p $1 else # If no parameter is nice the current pid (bash). ionice -c3 -p$$ ; renice -n 19 -p $$ fi } #------------------------------------------------------------- # String functions. #------------------------------------------------------------- # substring word start [length] substring() { if [ $# -lt 2 ]; then echo "Usage: substring word start [length]" return 1 fi if [ -z $3 ] then echo ${1:$2} else echo ${1:$2:$3} fi } # Get length of string. strlen() { if [ $# -ne 1 ]; then echo "Usage: length word" return 1 fi echo ${#1} } # Convert string to upper-case. strupper() { if [ $# -lt 1 ]; then echo "Usage: upper word" return 1 fi echo ${@^^} } # Convert string to lower-case. strlower() { if [ $# -lt 1 ]; then echo "Usage: lower word" return 1 fi echo ${@,,} } # Replace part of string with another. strreplace() { if [ $# -ne 3 ]; then echo "Usage: replace string substring replacement" return 1 fi echo ${1/$2/$3} } # Replace all parts of a string with another. strreplaceall() { if [ $# -ne 3 ]; then echo "Usage: replace string substring replacement" return 1 fi echo ${1//$2/$3} } # Find index of specified string. strindex() { if [ $# -ne 2 ]; then echo "Usage: index string substring" return 1 fi expr index $1 $2 } # Surround lines with quotes (useful in pipes). strquote() { echo "$@" | /bin/sed 's/^/"/;s/$/"/' ; } # Surround string with whatever is given as 2nd param. # # Example: # strsurround abc 123 # strsurround abc \" # strsurround abc \\\\ strsurround() { if [ $# -ne 2 ] then echo Usage: surround string surround-with e.g. surround hello \\\\ return 1 fi echo $1 | sed "s/^/$2/;s/$/$2/" ; } #------------------------------------------------------------- # USB functions. #------------------------------------------------------------- # Need to figure out which drive your usb is assigned? Functions work the same way as an alias. Simply copy the line into your .profile/.bashrc file. Then type: myusb myusb() { usb_array=();while read -r -d $'\n'; do usb_array+=("$REPLY"); done < <(find /dev/disk/by-path/ -type l -iname \*usb\*scsi\* -not -iname \*usb\*scsi\*part* -print0 | xargs -0 -iD readlink -f D | cut -c 8) && for usb in "${usb_array[@]}"; do echo "USB drive assigned to sd$usb"; done; }