🖥️function
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the function command with important options and switches using examples.
268 minute read
▁ ▂ ▃ ▄ ꧁ 🔴☠ COMMANDLINE-KUNGFU WITH CHEATSHEETS ☠🔴꧂▅ ▃ ▂ ▁
# ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗
# ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║
# █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║
# ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║
# ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║
# ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
# Define a bash function to interactively pick a subdirectory to cd into
############################################################################################################################################
###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS
############################################################################################################################################
#if [ -f ~/.bash_functions ]; then
# . ~/.bash_functions
#fi
# Benötigte Programme:
#===============================
# sudo apt-get install geoip-bin html2text mercurial madplay festival weather-util weather-util-data gawk w3m python-pip youtube-dl gnuplot ispell dict moreutils tree txt2html zenity lsdvd vobcopy python-webkit geoip-bin mpg321
# Benötigt Python3 und ist veraltet
# sudo pip install mps-youtube
# für mencoder werden deb-multimedia sources.list benötigt
# mencoder
# veraltet
# python-gtkmozembed xulrunner-2.0 remastersys python-pisa
###### Download all images from a 4chan thread
function 4chanimages()
{
curl -s http://boards.4chan.org/wg/|sed -r 's/.*href="([^"]*).*/\1\n/g'|grep images|xargs wget
}
###### Urlencoding with one pure BASH builtin
function URLEncode { local dataLength="${#1}"; local index; for ((index = 0;index < dataLength;index++)); do local char="${1:index:1}"; case $char in [a-zA-Z0-9.~_-]) printf "$char"; ;; *) printf "%%%02X" "'$char"; ;; esac; done; }
# URLEncode https://www.commandlinefu.com/commands/by/emphazer
# opposite of https://www.commandlinefu.com/commands/view/10014/urldecoding-with-one-pure-bash-builtin
# This is sample output
https%3A%2F%2Fwww.commandlinefu.com%2Fcommands%2Fby%2Femphazer
function csv2json() { for file in $@; do python -c "import csv,json,fileinput; print(json.dumps(list(csv.reader(fileinput.input()))))" "$file" 1> "${file%%csv}json"; done; }
# Convert CSV to JSON - Python3 and Bash function Is written for python3 and is very easy to use. csv2json *csv will convert all files ending in csv to json. eg csv2json file.csv will output a file to file.json
function dockpage() { lynx -width=180 --dump https://docs.docker.com/v1.11/engine/reference/commandline/$1/ | sed -n '/^Usage/,/On this page/{/On this page/b;p}'; }
# Shows the online version of docker's man related a command. Docker is local man pages are (often) half of what you have online, so I wanted that as local man.
function curlh() { x="$(curl -Is -w '%{http_code}' "$@")"; if [[ "$(tail -n 1 <<< "$x")" == [45]* ]]; then curl -is "$@" | awk '{ if (!NF) { exit }; print }'; else head -n -1 <<< "$x"; fi; }
# Get only headers from a website with curl even if it does not support HEAD. Some sites running on basic web servers do not support the HEAD request, so using "curl -I" on them does not work. This will automatically try "curl -I" at first and if that fails with a 4xx or 5xx status code, it falls back to "curl -i" and prints only the headers from that.
# setproxy on cmd
function setproxy() {
export {http,https,ftp}_proxy='http://PROXYUSER:[email protected]:8080'
}
function unsetproxy() {
unset {http,https,ftp}_proxy
}
# Check what a color code will look like by making a function to display them. I'm having one side of this conversation right now without the benefit of the other side.
function showcolor(){
display -size 400x400 "xc:$1" ;
}; showcolor '#6495ED'
# Generate Random Text based on Length
function genRandomText() {
local n=$1; while [ $((n--)) -gt 0 ]; do printf "\x$(printf %x $((RANDOM % 26 + 65)))" ; done ; echo ;
}
# function to compute what percentage of X is Y? Where percent/100 = X/Y => percent=100*X/Y
# This function make it easy to compute X/Y as a percentage. The name "wpoxiy" is an acronym of "what percentage of X is Y" Show Sample Output
#
# $ wpoxiy 65788574 1269501
# 1.92%
#
# $ wpoxiy 30 10
# 33.33%
# What percentage of X is Y? Where percent/100 = X/Y => percent=100*X/Y
# Example: wpoxiy 10 5 # 50.00%
# Example: wpoxiy 30 10 # 33.33%
function wpoxiy () {
echo $(bc <<< "scale=2; y=${1}; x=${2}; percent=x*100/y; percent")"%";
}
# Generate Random Text based on Length -> Random text of length "$1" without the useless cat command.
function genRandomText() {
tr -cd '[:alpha:]' < /dev/urandom | head -c "$1";
}
# small CPU benchmark with PI, bc and time. -> 4 cores with 2500 pi digits CPUBENCH 4 2500 . every core will use 100% cpu and you can see how fast they calculate it. if you do 50000 digitits and more it can take hours or days Show Sample Output
function CPUBENCH() {
local CPU="${1:-1}"; local SCALE="${2:-5000}"; { for LOOP in `seq 1 $CPU`; do { time echo "scale=${SCALE}; 4*a(1)" | bc -l -q | grep -v ^"[0-9]" & } ; done }; echo "Cores: $CPU"; echo "Digit: $SCALE" ;
}
# Show all files sorted by date -> a quick function for searching changed files. just copy it in the bash Show Sample Output
function FINDDATE() {
LOCATION="${1:-.}"; find ${LOCATION} -type f -print0 | xargs -0 stat -c "%y %n" | sort | sed 's/.\([0-9]\)\{9,\} +0[1-2]00/\t/' | sed 's/ /\t/g'
}
# Function to draw a regular polygon using ImageMagick commands. Ex: poly 8 280 Credit to Digital Trauma on StackEx. CodeGolf
function poly(){
c=`bc -l <<<"for(;i++<$1;){t=6.28*i/$1;print s(t)*$2+$2,\",\";c(t)*$2+$2}"`;convert -size $[$2*2]x$[$2*2] xc: -draw "polygon $c" png:-|display;
}
# Abort the whole script from a function
trap "exit 1" TERM
export TOP_PID=$$
function fatal(){
echo "Goodbye"
kill -s TERM $TOP_PID
}
echo "Function call will abort"
echo $(func)
echo "This will never be printed"
# Find inside specific file type function
function findin() {
find . -type f -name "*.$1" | xargs ack $2
}
###### Add a function you've defined to .bashrc
function addfunction() { declare -f $1 >> ~/.bashrc ; }
# You can put this in your shell rc to *help* protect yourself *specifically* from :(){ :|:& };: #bash
:(){ true; };readonly -f :
#
sec2dhms()
{
declare -i SS="$1" D=$(( SS / 86400 )) H=$(( SS % 86400 / 3600 )) M=$(( SS % 3600 / 60 )) S=$(( SS % 60 )) [ "$D" -gt 0 ] && echo -n "${D}:" [ "$H" -gt 0 ] && printf "%02g:" "$H" printf "%02g:%02g\n" "$M" "$S"
}
## Convert seconds to [DD:][HH:]MM:SS
# Converts any number of seconds into days, hours, minutes and seconds.
sec2dhms()
{
declare -i SS="$1"
D=$(( SS / 86400 ))
H=$(( SS % 86400 / 3600 ))
M=$(( SS % 3600 / 60 ))
S=$(( SS % 60 ))
[ "$D" -gt 0 ] && echo -n "${D}:"
[ "$H" -gt 0 ] && printf "%02g:" "$H"
printf "%02g:%02g\n" "$M" "$S"
}
shebang () { printf '%s\n' 0a '#!'"$1" . w | ed -s "$2" ; }
# Retrofit a shebang to an existing script
# Function to add a shebang to an existing script, handy if you forgot to add it in the first place.
videospeed() { vname="$1"; speedc="$2"; vs=$(python3 -c "print(1/$speedc)"); aspeed=$(python3 -c "print(1*$speedc)"); ffmpeg -i "$vname" -filter:a "atempo=$aspeed" -filter:v "setpts=$vs*PTS" "${3:-converted_$1}"; }
# Speed up or slow down video (and audio)
# Usage:
videospeed video_filename speedchange newfilename
videospeed foo.mp4 0.5 foo_slow.mp4
# Range of 0.5 (50%) - 2.0 (200%) is valid.
lc() { od="$1"; nd="$2"; of=$3; nf=$4; cp -rl "$od" "$nd"; parallel -0 "ffmpeg -i {1} -loglevel error -q:a 6 {1.}.{2} && { rm {1}; echo {1.}.{2}; }" :::: <(find "$nd" -type f -iname \*$of -print0) ::: "$nf"; }
# Convert entire audio library in parallel
# Uses parallel processing
# Reiteration of my earlier command -> https://www.commandlinefu.com/commands/view/15246/convert-entire-music-library
# Usage
lc Old_Directory New_DIrectory Old_Format New_Format
lc ~/Music ~/Music_ogg mp3 ogg
function cdb()
{
select dir in $(find -type d -name "$1" -not -path '*/\.*' -prune)
do cd "${dir}" && break
done
}
# Extract Function Linux Bash
# Extract archives - use: extract <file>
# Based on http://dotfiles.org/~pseup/.bashrc
function extract() {
if [ -f "$1" ] ; then
local filename=$(basename "$1")
local foldername="${filename%%.*}"
local fullpath=`perl -e 'use Cwd "abs_path";print abs_path(shift)' "$1"`
local didfolderexist=false
if [ -d "$foldername" ]; then
didfolderexist=true
read -p "$foldername already exists, do you want to overwrite it? (y/n) " -n 1
echo
if [[ $REPLY =~ ^[Nn]$ ]]; then
return
fi
fi
mkdir -p "$foldername" && cd "$foldername"
case $1 in
*.tar.bz2) tar xjf "$fullpath" ;;
*.tar.gz) tar xzf "$fullpath" ;;
*.tar.xz) tar Jxvf "$fullpath" ;;
*.tar.Z) tar xzf "$fullpath" ;;
*.tar) tar xf "$fullpath" ;;
*.taz) tar xzf "$fullpath" ;;
*.tb2) tar xjf "$fullpath" ;;
*.tbz) tar xjf "$fullpath" ;;
*.tbz2) tar xjf "$fullpath" ;;
*.tgz) tar xzf "$fullpath" ;;
*.txz) tar Jxvf "$fullpath" ;;
*.zip) unzip "$fullpath" ;;
*) echo "'$1' cannot be extracted via extract()" && cd .. && ! $didfolderexist && rm -r "$foldername" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
#------------------------------------------------------------------------------#
function cdb() { select dir in $(find -type d -name "$1" -not -path '*/\.*' -prune); do cd "${dir}" && break; done }
# Define a bash function to interactively pick a subdirectory to cd into
# Bash autocomplete ssh hosts
gistfile1.txt
_complete_ssh_hosts ()
{
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
comp_ssh_hosts=`cat ~/.ssh/known_hosts | \
cut -f 1 -d ' ' | \
sed -e s/,.*//g | \
grep -v ^# | \
uniq | \
grep -v "\[" ;
cat ~/.ssh/config | \
grep "^host " | \
awk '{print $2}'
`
COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur))
return 0
}
complete -F _complete_ssh_hosts ssh
###### to export private OpenPGP keys to a file for safe keeping and potential restoration - using 'mykeys', put the appropriate GPG key after you type this function
function exportmykeys_private()
{
gpg --list-secret-keys
echo -n "Please enter the appropriate private key...
Look for the line that starts something like "sec 1024D/".
The part after the 1024D is the key_id.
...like this: '2942FE31'...
"
read MYKEYPRIV
gpg -ao Private_Keys-private.key --export-secret-keys "$MYKEYPRIV"
echo -n "All done."
}
###### to export public OpenPGP keys to a file for safe keeping and potential restoration- using 'mykeys', put the appropriate GPG key after you type this function
function exportmykeys_public()
{
gpg --list-keys
echo -n "Please enter the appropriate public key...
Look for line that starts something like "pub 1024D/".
The part after the 1024D is the public key_id.
...like this: '2942FE31'...
"
read MYKEYPUB
gpg -ao Public_Keys-public.key --export "$MYKEYPUB"
echo -n "All done."
}
###### to restore your public and private OpenPGP keys from Public_Key-public.key and Private_Keys-private.key files:
function restoremykeys()
{
echo -n "Please enter the full path to Public keys (spaces are fine)...
Example: '/home/(your username)/Public_Key-public.key'...
"
read MYKEYS_PUBLIC_LOCATION
gpg --import "$MYKEYS_PUBLIC_LOCATION"
echo -n "Please enter the full path to Private keys (spaces are fine)...
Example: '/home/(your username)/Private_Keys-private.key'...
"
read MYKEYS_PRIVATE_LOCATION
gpg --import "$MYKEYS_PRIVATE_LOCATION"
echo -n "All done."
}
###### to setup new public and private OpenPGP keys
function setupmykeys()
{
# Generate new key
gpg --gen-key
# Publish new key to Ubuntu keyserver
gpg --keyserver hkp://keyserver.ubuntu.com --send-keys
# Import an OpenPGP key
gpg --fingerprint
# Verify new key
read -sn 1 -p "Before you continue, you must enter the fingerprint
in the appropriate place in your Launchpad PPA on their website...
Once you have successfully inputed it, wait for your email before
you press any key to continue...
"
gedit $HOME/file.txt
read -sn 1 -p "Once you have received your email from Launchpad to
verify your new key, copy and paste the email message received upon
import of OpenPGP key from "-----BEGIN PGP MESSAGE-----" till
"-----END PGP MESSAGE-----" to the 'file.txt' in your home folder
that was just opened for you
Once you have successfully copied and pasted it, save it and
press any key to continue...
"
gpg -d $HOME/file.txt
echo -n "All done."
}
# Text alignment
#------------------------------------------////
###### center text in console with simple pipe like
function align_center() { l="$(cat -)"; s=$(echo -e "$l"| wc -L); echo "$l" | while read l;do j=$(((s-${#l})/2));echo "$(while ((--j>0)); do printf " ";done;)$l";done;} #; ls --color=none / | center
###### right-align text in console using pipe like ( command | right )
function align_right() { l="$(cat -)"; [ -n "$1" ] && s=$1 || s=$(echo -e "$l"| wc -L); echo "$l" | while read l;do j=$(((s-${#l})));echo "$(while ((j-->0)); do printf " ";done;)$l";done;} #; ls --color=none / | right 150
# Network information and IP address stuff
#------------------------------------------////
###### get all IPs via ifconfig
function allips()
{
sudo ifconfig | awk '/inet / {sub(/addr:/, "", $2); print $2}'
}
###### clear iptables rules safely
function clearIptables()
{
iptables -P INPUT ACCEPT; iptables -P FORWARD ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F; iptables -X; iptables -L
}
###### online check
function connected() { ping -c1 -w2 google.com > /dev/null 2>&1; }
function connected_() { rm -f /tmp/connect; http_proxy='http://a.b.c.d:8080' wget -q -O /tmp/connect http://www.google.com; if [[ -s /tmp/connect ]]; then return 0; else return 1; fi; }
###### check if a remote port is up using dnstools.com - (i.e. from behind a firewall/proxy)
function cpo() { [[ $# -lt 2 ]] && echo 'need IP and port' && return 2; [[ `wget -q "http://dnstools.com/?count=3&checkp=on&portNum=$2&target=$1&submit=Go\!" -O - |grep -ic "Connected successfully to port $2"` -gt 0 ]] && echo OPEN || echo CLOSED; }
###### find an unused unprivileged TCP port
function findtcp()
{
(netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq 32768 61000) | sort -n | uniq -u | head -n 1
}
###### geoip lookup (need geoip database: sudo apt-get install geoip-bin)
function geoip() {
sudo geoiplookup $1
}
###### geoip information - requires 'html2text': sudo apt-get install html2text
function geoiplookup() { curl -A "Mozilla/5.0" -s "http://www.geody.com/geoip.php?ip=$1" | grep "^IP.*$1" | html2text; }
###### get IP address of a given interface - Example: getip lo - Example: getip eth0 # this is the default
function getip() { lynx -dump http://whatismyip.org/; }
###### display private IP
function ippriv()
{
sudo ifconfig eth0|grep "inet adr"|awk '{print $2}'|awk -F ':' '{print $2}'
}
###### ifconfig connection check
function ips()
{
if [ "$OS" = "Linux" ]; then
for i in $( /sbin/ifconfig | grep ^e | awk '{print $1}' | sed 's/://' ); do echo -n "$i: "; /sbin/ifconfig $i | perl -nle'/dr:(\S+)/ && print $1'; done
elif [ "$OS" = "Darwin" ]; then
for i in $( /sbin/ifconfig | grep ^e | awk '{print $1}' | sed 's/://' ); do echo -n "$i: "; /sbin/ifconfig $i | perl -nle'/inet (\S+)/ && print $1'; done
fi
}
###### geolocate a given IP address
function ip2loc() { wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICountry\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g'; }
###### ip2locall
function ip2locall() {
# best if used through a proxy, as ip2loc's free usage only lets you search a maximum of 20 times per day
# currently set on using a proxy through tor; if don't want that, just comment out the two 'export..' and 'unset...' lines
export http_proxy='http://localhost:8118'
export https_proxy='http://localhost:8118'
echo ""
echo "Country:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICountry\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Region (State, Province, Etc.):"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIRegion\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "City:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICity\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Latitude:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILatitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Longitude:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILongitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "ZIP Code:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIZIPCode\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Time Zone:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblITimeZone\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Net Speed:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblINetSpeed\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "ISP:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIISP\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Domain:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIDomain\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "IDD Code:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIIDDCode\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Area Code:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIAreaCode\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Weather Station:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIWeatherStation\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "MCC:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIMCC\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "MNC:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIMNC\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Mobile Brand:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIMobileBrand\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
unset http_proxy
unset https_proxy
}
###### ip2locate
function ip2locate() {
# best if used through a proxy, as ip2loc's free usage only lets you search a maximum of 20 times per day
# currently set on using a proxy through tor; if don't want that, just comment out the two 'export..' and 'unset...' lines
export http_proxy='http://localhost:8118'
export https_proxy='http://localhost:8118'
echo ""
echo "Country:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICountry\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Region (State, Province, Etc.):"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIRegion\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "City:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICity\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Latitude:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILatitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
echo "Longitude:"
wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILongitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g';
echo ""
unset http_proxy
unset https_proxy
}
###### find the IP addresses that are currently online in your network
function localIps()
{
for i in {1..254}; do
x=`ping -c1 -w1 192.168.1.$i | grep "%" | cut -d"," -f3 | cut -d"%" -f1 | tr '\n' ' ' | sed 's/ //g'`
if [ "$x" == "0" ]; then
echo "192.168.1.$i"
fi
done
}
####### Meine momentane IP-Adresse
function myipis ()
{
echo MyIP:
elinks -dump http://checkip.dyndns.org:8245/ | grep "Current IP Address" | cut -d":" -f2 | cut -d" " -f2
}
###### myip - finds your current IP if your connected to the internet
function myip()
{
lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | awk '{ print $4 }' | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g'
}
###### netinfo - shows network information for your system
function netinfo()
{
echo "--------------- Network Information ---------------"
/sbin/ifconfig | awk /'inet addr/ {print $2}'
/sbin/ifconfig | awk /'Bcast/ {print $3}'
/sbin/ifconfig | awk /'inet addr/ {print $4}'
/sbin/ifconfig | awk /'HWaddr/ {print $4,$5}'
myip=`lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g' `
echo "${myip}"
echo "---------------------------------------------------"
}
###### check whether or not a port on your box is open
function portcheck() { for i in $@;do curl -s "deluge-torrent.org/test-port.php?port=$i" | sed '/^$/d;s/<br><br>/ /g';done; }
###### scp sending
function scpsend()
{
scp -P PORTNUMBERHERE "$@" [email protected]:/var/www/html/pathtodirectoryonremoteserver/;
}
###### show ip
function show_ip()
{
case $1 in
*help | "" )
echo -e "\n${ewhite}Usage:\n"
echo -e "${eorange}show_ip${ewhite} |${egreen} <interface> ${eiceblue}[show ip-address for <interface>]\
\n${eorange}show_ip${ewhite} |${egreen} external${eiceblue} [show external ip address]\n"
tput sgr0
;;
*external )
wget -q -O - http://showip.spamt.net/
;;
* )
LANG=C /sbin/ifconfig $1 | grep 'inet addr:' | cut -d: -f2 | gawk '{ print $1}'
;;
esac
}
###### display the ttl of a hostname in a human readable form (packet timetrans veraltet)
#function ttl()
#{
# /usr/sbin/timetrans -count $(dig +noquestion +noadditional +noauthority $1 | grep "^$1" | awk '{print $2}')
#}
###### show Url information - Usage: url-info "ur"
function url-info()
{
doms=$@
if [ $# -eq 0 ]; then
echo -e "No domain given\nTry $0 domain.com domain2.org anyotherdomain.net"
fi
for i in $doms; do
_ip=$(host $i|grep 'has address'|awk {'print $4'})
if [ "$_ip" == "" ]; then
echo -e "\nERROR: $i DNS error or not a valid domain\n"
continue
fi
ip=`echo ${_ip[*]}|tr " " "|"`
echo -e "\nInformation for domain: $i [ $ip ]\nQuerying individual IPs"
for j in ${_ip[*]}; do
echo -e "\n$j results:"
whois $j |egrep -w 'OrgName:|City:|Country:|OriginAS:|NetRange:'
done
done
}
###### cleanly list available wireless networks (using iwlist)
function wscan()
{
iwlist wlan0 scan | sed -ne 's#^[[:space:]]*\(Quality=\|Encryption key:\|ESSID:\)#\1#p' -e 's#^[[:space:]]*\(Mode:.*\)$#\1\n#p'
}
####### Show all strings (ASCII & Unicode) in a file
function allStrings() { cat "$1" | tr -d "\0" | strings ; }
####### Find all videos under current directory using - MIME a.k.a not using extension
function allVideos() { find ./ -type f -print0 | xargs -0 file -iNf - | grep ": video/" | cut -d: -f1 ; }
# Miscellaneous Fun
#------------------------------------------////
###### anagrams
function anagrams()
{
cat > "/tmp/anagrams.py" <<"End-of-message"
#!/usr/bin/python
infile = open ("/usr/share/dict/words", "r")
## "dict" is a reserved word
words_in = infile.readlines()
scrambled = raw_input("Enter the scrambled word: ")
scrambled = scrambled.lower()
scrambled_list = list(scrambled)
scrambled_list.sort()
for word in words_in:
word_list = list(word.strip().lower())
word_list.sort()
## you don't really have to compare lengths when using lists as the
## extra compare takes about as long as finding the first difference
if word_list == scrambled_list:
print word, scrambled
End-of-message
chmod +x "/tmp/anagrams.py"
"/tmp/anagrams.py" "$1"
rm "/tmp/anagrams.py"
}
function anagram_() { function s() { sed 's/[[:space:]]*//g;s/./\n\0/g'<<<"$@"|tr A-Z a-z|sort;};cmp -s <(s $1) <(s $2)||echo -n "not ";echo anagram; }
###### random Cyanide and Happiness comics from explosm.net
function cyanide() { display "$(wget -q http://explosm.net/comics/random/ -O - | grep -Po 'http://www.explosm.net/db/files/Comics/*/[^"]+(png|jpg|jpeg)')"; }
###### fake error string
function error()
{
while true; do awk '{ print ; system("let R=$RANDOM%10; sleep $R") }' compiler.log; done
}
###### stupid funny face
function funny_face() {
_ret=$?; if test $_ret -ne 0; then echo "0_0->ret=$_ret"; set ?=$_ret; unset _ret; else echo "^_^"; fi
}
###### pretend to be busy in office to enjoy a cup of coffee
function grepcolor()
{
cat /dev/urandom | hexdump -C | grep --color=auto "ca fe"
}
###### a simple number guessing game
function hilow()
{
biggest=1000 # maximum number possible
guess=0 # guessed by player
guesses=0 # number of guesses made
number=$(( $$ % $biggest )) # random number, 1 .. $biggest
while [ $guess -ne $number ] ; do
echo -n "Guess? " ; read guess
if [ "$guess" -lt $number ] ; then
echo "... bigger!"
elif [ "$guess" -gt $number ] ; then
echo "... smaller!"
fi
guesses=$(( $guesses + 1 ))
done
echo "Right!! Guessed $number in $guesses guesses."
}
###### watch the National debt clock
function natdebt()
{
watch -n 10 "wget -q http://www.brillig.com/debt_clock -O - | grep debtiv.gif | sed -e 's/.*ALT=\"//' -e 's/\".*//' -e 's/ //g'"
}
######
function oneliners()
{
w3m -dump_source http://www.onelinerz.net/random-one-liners/1/ | awk ' /.*<div id=\"oneliner_[0-9].*/ {while (! /\/div/ ) { gsub("\n", ""); getline; }; gsub (/<[^>][^>]*>/, "", $0); print $0}'
}
###### random cowsay stuff
function random_cow()
{
files=(/usr/share/cowsay/cows/*)
printf "%s\n" "${files[RANDOM % ${#files}]}"
}
####### Temporarily add to PATH
function apath()
{
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
echo "Temporarily add to PATH"
echo "usage: apath [dir]"
else
PATH=$1:$PATH
fi
}
###### Function you want after you've overwritten some - important file using > instead of >> ^^
function append() {
lastarg="${!#}"
echo "${@:1:$(($#-1))}" >> "$lastarg"
}
####### Common commands piped through grep
function aptg() # debian specific.
{
if [ $# -lt 1 ] || [ $# -gt 1 ]; then
echo "search debian package list"
echo "usage: aptg [program/keyword]"
else
apt-cache search $1 | sort | less
fi
}
###### grep by paragraph instead of by line
function grepp() { [ $# -eq 1 ] && perl -00ne "print if /$1/i" || perl -00ne "print if /$1/i" < "$2";}
function hgg()
{
if [ $# -lt 1 ] || [ $# -gt 1 ]; then
echo "search bash history"
echo "usage: mg [search pattern]"
else
history | grep -i $1 | grep -v hg
fi
}
function lsofg()
{
if [ $# -lt 1 ] || [ $# -gt 1 ]; then
echo "grep lsof"
echo "usage: losfg [port/program/whatever]"
else
lsof | grep -i $1 | less
fi
}
function psg()
{
if [ $# -lt 1 ] || [ $# -gt 1 ]; then
echo "grep running processes"
echo "usage: psg [process]"
else
ps aux | grep USER | grep -v grep
ps aux | grep -i $1 | grep -v grep
fi
}
####### To show Apt Log History
function apt-history() {
case "$1" in
install)
cat /var/log/dpkg.log | grep 'install '
;;
upgrade|remove)
cat /var/log/dpkg.log | grep $1
;;
rollback)
cat /var/log/dpkg.log | grep upgrade | \
grep "$2" -A10000000 | \
grep "$3" -B10000000 | \
awk '{print $4"="$5}'
;;
*)
cat /var/log/dpkg.log
;;
esac
}
####### Undo apt-get build-dep (remove build dependencies) #
function aptitude-remove-dep() { sudo aptitude markauto $(apt-cache showsrc "$1" | grep Build-Depends | perl -p -e 's/(?:[\[(].+?[\])]|Build-Depends:|,|\|)//g'); }
####### Arch-wiki-docs simple search
function archwikisearch() {
# old version
# cd /usr/share/doc/arch-wiki/html/
# grep -i "$1" index.html | sed 's/.*HREF=.\(.*\.html\).*/\1/g' | xargs opera -newpage
cd /usr/share/doc/arch-wiki/html/
for i in $(grep -li $1 *)
do
STRING=`grep -m1 -o 'wgTitle = "[[:print:]]\+"' $i`
LEN=${#STRING}
let LEN=LEN-12
STRING=${STRING:11:LEN}
LOCATION="/usr/share/doc/arch-wiki/html/$i"
echo -e " \E[33m$STRING \E[37m$LOCATION"
done
}
# Numerical conversions and numbers stuff
#------------------------------------------////
###### convert arabic to roman numerals
function arabic2roman() {
echo $1 | sed -e 's/1...$/M&/;s/2...$/MM&/;s/3...$/MMM&/;s/4...$/MMMM&/
s/6..$/DC&/;s/7..$/DCC&/;s/8..$/DCCC&/;s/9..$/CM&/
s/1..$/C&/;s/2..$/CC&/;s/3..$/CCC&/;s/4..$/CD&/;s/5..$/D&/
s/6.$/LX&/;s/7.$/LXX&/;s/8.$/LXXX&/;s/9.$/XC&/
s/1.$/X&/;s/2.$/XX&/;s/3.$/XXX&/;s/4.$/XL&/;s/5.$/L&/
s/1$/I/;s/2$/II/;s/3$/III/;s/4$/IV/;s/5$/V/
s/6$/VI/;s/7$/VII/;s/8$/VIII/;s/9$/IX/
s/[0-9]//g'
}
###### convert ascii
function asc2all() {
if [[ $1 ]]; then
echo "ascii $1 = binary $(asc2bin $1)"
echo "ascii $1 = octal $(asc2oct $1)"
echo "ascii $1 = decimal $(asc2dec $1)"
echo "ascii $1 = hexadecimal $(asc2hex $1)"
echo "ascii $1 = base32 $(asc2b32 $1)"
echo "ascii $1 = base64 $(asc2b64 $1)"
fi
}
######
function asc2bin() {
if [[ $1 ]]; then
echo "obase=2 ; $(asc2dec $1)" | bc
fi
}
######
function asc2b64() {
if [[ $1 ]]; then
echo "obase=64 ; $(asc2dec $1)" | bc
fi
}
######
function asc2b32() {
if [[ $1 ]]; then
echo "obase=32 ; $(asc2dec $1)" | bc
fi
}
######
function asc2dec() {
if [[ $1 ]]; then
printf '%d\n' "'$1'"
fi
}
######
function asc2hex() {
if [[ $1 ]]; then
echo "obase=16 ; $(asc2dec $1)" | bc
fi
}
######
function asc2oct() {
if [[ $1 ]]; then
echo "obase=8 ; $(asc2dec $1)" | bc
fi
}
###### Averaging columns of numbers - Computes a columns average in a file. Input parameters = column number and optional pattern.
function avg() { awk "/$2/{sum += \$$1; lc += 1;} END {printf \"Average over %d lines: %f\n\", lc, sum/lc}"; }
###### convert binaries
function bin2all() {
if [[ $1 ]]; then
echo "binary $1 = octal $(bin2oct $1)"
echo "binary $1 = decimal $(bin2dec $1)"
echo "binary $1 = hexadecimal $(bin2hex $1)"
echo "binary $1 = base32 $(bin2b32 $1)"
echo "binary $1 = base64 $(bin2b64 $1)"
echo "binary $1 = ascii $(bin2asc $1)"
fi
}
######
function bin2asc() {
if [[ $1 ]]; then
echo -e "\0$(printf %o $((2#$1)))"
fi
}
######
function bin2b64() {
if [[ $1 ]]; then
echo "obase=64 ; ibase=2 ; $1" | bc
fi
}
######
function bin2b32() {
if [[ $1 ]]; then
echo "obase=32 ; ibase=2 ; $1 " | bc
fi
}
######
function bin2dec() {
if [[ $1 ]]; then
echo $((2#$1))
fi
}
######
function bin2hex() {
if [[ $1 ]]; then
echo "obase=16 ; ibase=2 ; $1" | bc
fi
}
######
function bin2oct() {
if [[ $1 ]]; then
echo "obase=8 ; ibase=2 ; $1" | bc
fi
}
###### simple calculator to 4 decimals
function calc() {
echo "scale=4; $1" | bc
}
###### temperature conversion
function cel2fah() {
if [[ $1 ]]; then
echo "scale=2; $1 * 1.8 + 32" | bc
fi
}
######
function cel2kel() {
if [[ $1 ]]; then
echo "scale=2; $1 + 237.15" | bc
fi
}
######
function fah2cel() {
if [[ $1 ]]; then
echo "scale=2 ; ( $1 - 32 ) / 1.8" | bc
fi
}
######
function fah2kel() {
if [[ $1 ]]; then
echo "scale=2; ( $1 + 459.67 ) / 1.8 " | bc
fi
}
######
function kel2cel() {
if [[ $1 ]]; then
echo "scale=2; $1 - 273.15" | bc
fi
}
######
function kel2fah() {
if [[ $1 ]]; then
echo "scale=2; $1 * 1.8 - 459,67" | bc
fi
}
###### Output an ASCII character given its decimal equivalent
function chr() { printf \\$(($1/64*100+$1%64/8*10+$1%8)); }
###### the notorious "hailstone" or Collatz series.
function collatz()
{
# get the integer "seed" from the command-line to generate the integer "result"
# if NUMBER is even, divide by 2, or if odd, multiply by 3 and add 1
# the theory is that every sequence eventually settles down to repeating "4,2,1..." cycles
MAX_ITERATIONS=200
# For large seed numbers (>32000), try increasing MAX_ITERATIONS.
h=${1:-$$} # Seed. # Use $PID as seed, #+ if not specified as command-line arg.
echo
echo "C($h) --- $MAX_ITERATIONS Iterations"
echo
for ((i=1; i<=MAX_ITERATIONS; i++))
do
COLWIDTH=%7d
printf $COLWIDTH $h
let "remainder = h % 2"
if [ "$remainder" -eq 0 ] # Even?
then
let "h /= 2" # Divide by 2.
else
let "h = h*3 + 1" # Multiply by 3 and add 1.
fi
COLUMNS=10 # Output 10 values per line.
let "line_break = i % $COLUMNS"
if [ "$line_break" -eq 0 ]
then
echo
fi
done
echo
}
###### temperature conversion script that lets the user enter a temperature in any of Fahrenheit, Celsius or Kelvin and receive the equivalent temperature in the other two units as the output. - usage: convertatemp F100 (if don't put F,C, or K, default is F)
function convertatemp(){
if uname | grep 'SunOS'>/dev/null ; then
echo "Yep, SunOS, let\'s fix this baby"
PATH="/usr/xpg4/bin:$PATH"
fi
if [ $# -eq 0 ] ; then
cat << EOF >&2
Usage: $0 temperature[F|C|K]
where the suffix:
F indicates input is in Fahrenheit (default)
C indicates input is in Celsius
K indicates input is in Kelvin
EOF
fi
unit="$(echo $1|sed -e 's/[-[[:digit:]]*//g' | tr '[:lower:]' '[:upper:]' )"
temp="$(echo $1|sed -e 's/[^-[[:digit:]]*//g')"
case ${unit:=F}
in
F ) # Fahrenheit to Celsius formula: Tc = (F -32 ) / 1.8
farn="$temp"
cels="$(echo "scale=2;($farn - 32) / 1.8" | bc)"
kelv="$(echo "scale=2;$cels + 273.15" | bc)"
;;
C ) # Celsius to Fahrenheit formula: Tf = (9/5)*Tc+32
cels=$temp
kelv="$(echo "scale=2;$cels + 273.15" | bc)"
farn="$(echo "scale=2;((9/5) * $cels) + 32" | bc)"
;;
K ) # Celsius = Kelvin + 273.15, then use Cels -> Fahr formula
kelv=$temp
cels="$(echo "scale=2; $kelv - 273.15" | bc)"
farn="$(echo "scale=2; ((9/5) * $cels) + 32" | bc)"
esac
echo "Fahrenheit = $farn"
echo "Celsius = $cels"
echo "Kelvin = $kelv"
}
###### convert hexadecimal numbers to decimals
function dec() { printf "%d\n" $1; }
###### convert decimals to hexadecimal numbers
function hex() { printf "0x%08x\n" $1; }
###### convert decimals
function dec2all() {
if [[ $1 ]]; then
echo "decimal $1 = binary $(dec2bin $1)"
echo "decimal $1 = octal $(dec2oct $1)"
echo "decimal $1 = hexadecimal $(dec2hex $1)"
echo "decimal $1 = base32 $(dec2b32 $1)"
echo "decimal $1 = base64 $(dec2b64 $1)"
echo "deciaml $1 = ascii $(dec2asc $1)"
fi
}
######
function dec2asc() {
if [[ $1 ]]; then
echo -e "\0$(printf %o 97)"
fi
}
######
function dec2bin() {
if [[ $1 ]]; then
echo "obase=2 ; $1" | bc
fi
}
######
function dec2b64() {
if [[ $1 ]]; then
echo "obase=64 ; $1" | bc
fi
}
######
function dec2b32() {
if [[ $1 ]]; then
echo "obase=32 ; $1" | bc
fi
}
######
function dec2hex() {
if [[ $1 ]]; then
echo "obase=16 ; $1" | bc
fi
}
######
function dec2oct() {
if [[ $1 ]]; then
echo "obase=8 ; $1" | bc
fi
}
###### number --- convert decimal integer to english words - total number Usage: dec2text 1234 -> one thousand two hundred thirty-four
function dec2text()
{
prog=`echo "$0" | sed -e 's/[^\/]*\///g'`
garbage=`echo "$*" | sed -e 's/[0-9,.]//g'`
if test ".$garbage" != "."; then
echo "$prog: Invalid character in argument." 1>&2
fi
case "$*" in
# This doesn't always seem to work.
# *[!0-9,.]* ) echo "$prog: Invalid character in argument." 1>&2; ;;
*.* ) echo "$prog: fractions not supported (yet)." 1>&2; ;;
'' ) echo "Usage: $prog [decimal integer]" 1>&2; ;;
esac
result=
eval set - "`echo ${1+\"$@\"} | sed -n -e '
s/[, ]//g
s/^00*/0/g
s/\(.\)\(.\)\(.\)$/\"\1 \2 \3\"/
:l
/[0-9][0-9][0-9]/{
s/\([^\" ][^\" ]*\)\([^\" ]\)\([^\" ]\)\([^\" ]\)/\1\"\2 \3 \4\"/g
t l
}
/^[0-9][0-9][0-9]/s/\([^\" ]\)\([^\" ]\)\([^\" ]\)/\"\1 \2 \3\"/
/^[0-9][0-9]/s/\([^\" ]\)\([^\" ]\)/\"\1 \2\"/
/^[0-9]/s/^\([^\" ][^\" ]*\)/\"\1\"/g;s/\"\"/\" \"/g
p'`"
while test $# -ne 0 ; do
eval `set - $1;
d3='' d2='' d1=''
case $# in
1 ) d1=$1 ;;
2 ) d2=$1 d1=$2 ;;
3 ) d3=$1 d2=$2 d1=$3 ;;
esac
echo "d3=\"$d3\" d2=\"$d2\" d1=\"$d1\""`
val1='' val2='' val3=''
case "$d3" in
1 ) val3=one ;; 6 ) val3=six ;;
2 ) val3=two ;; 7 ) val3=seven ;;
3 ) val3=three ;; 8 ) val3=eight ;;
4 ) val3=four ;; 9 ) val3=nine ;;
5 ) val3=five ;;
esac
case "$d2" in
1 ) val2=teen ;; 6 ) val2=sixty ;;
2 ) val2=twenty ;; 7 ) val2=seventy ;;
3 ) val2=thirty ;; 8 ) val2=eighty ;;
4 ) val2=forty ;; 9 ) val2=ninety ;;
5 ) val2=fifty ;;
esac
case "$val2" in
teen )
val2=
case "$d1" in
0 ) val1=ten ;; 5 ) val1=fifteen ;;
1 ) val1=eleven ;; 6 ) val1=sixteen ;;
2 ) val1=twelve ;; 7 ) val1=seventeen ;;
3 ) val1=thirteen ;; 8 ) val1=eighteen ;;
4 ) val1=fourteen ;; 9 ) val1=nineteen ;;
esac
;;
0 ) : ;;
* )
test ".$val2" != '.' -a ".$d1" != '.0' \
&& val2="${val2}-"
case "$d1" in
0 ) val2="$val2 " ;; 5 ) val1=five ;;
1 ) val1=one ;; 6 ) val1=six ;;
2 ) val1=two ;; 7 ) val1=seven ;;
3 ) val1=three ;; 8 ) val1=eight ;;
4 ) val1=four ;; 9 ) val1=nine ;;
esac
;;
esac
test ".$val3" != '.' && result="$result$val3 hundred "
test ".$val2" != '.' && result="$result$val2"
test ".$val1" != '.' && result="$result$val1 "
if test ".$d1$d2$d3" != '.000' ; then
case $# in
0 | 1 ) ;;
2 ) result="${result}thousand " ;;
3 ) result="${result}million " ;;
4 ) result="${result}billion " ;;
5 ) result="${result}trillion " ;;
6 ) result="${result}quadrillion " ;;
7 ) result="${result}quintillion " ;;
8 ) result="${result}sextillion " ;;
9 ) result="${result}septillion " ;;
10 ) result="${result}octillion " ;;
11 ) result="${result}nonillion " ;;
12 ) result="${result}decillion " ;;
13 ) result="${result}undecillion " ;;
14 ) result="${result}duodecillion " ;;
15 ) result="${result}tredecillion " ;;
16 ) result="${result}quattuordecillion " ;;
17 ) result="${result}quindecillion " ;;
18 ) result="${result}sexdecillion " ;;
19 ) result="${result}septendecillion " ;;
20 ) result="${result}octodecillion " ;;
21 ) result="${result}novemdecillion " ;;
22 ) result="${result}vigintillion " ;;
* ) echo "Error: number too large (66 digits max)." 1>&2; ;;
esac
fi
shift
done
set $result > /dev/null
case "$*" in
'') set zero ;;
esac
echo ${1+"$@"}
# number ends here
}
####### individual numbers - Usage: dec2text 1234 -> one two three four
function dec2text_()
{
n=$1
len=$(echo $n | wc -c)
len=$(( $len - 1 ))
for (( i=1; i<=$len; i++ ))
do
# get one digit at a time
digit=$(echo $n | cut -c $i)
# use case control structure to find digit equivalent in words
case $digit in
0) echo -n "zero " ;;
1) echo -n "one " ;;
2) echo -n "two " ;;
3) echo -n "three " ;;
4) echo -n "four " ;;
5) echo -n "five " ;;
6) echo -n "six " ;;
7) echo -n "seven " ;;
8) echo -n "eight " ;;
9) echo -n "nine " ;;
esac
done
# just print new line
echo ""
}
###### d2u
function d2u() {
if [[ -e "$1" ]]; then
sed -r 's/\r$//' -i "$1"
fi
}
###### u2d
function u2d() {
if [[ -e "$1" ]]; then
sed -r 's/$/\r/' -i "$1"
fi
}
###### factorial for integers
function factorial()
{
echo "Enter an integer: "
read n
# Below we define the factorial function in bc syntax
fact="define f (x) {
i=x
fact=1
while (i > 1) {
fact=fact*i
i=i-1
}
return fact
}"
# Below we pass the function defined above, and call it with n as a parameter and pipe it to bc
factorial=`echo "$fact;f($n)" | bc -l`
echo "$n! = $factorial"
}
###### convert hexadecimal numbers - hex2all
function hex2all() {
if [[ $1 ]]; then
echo "hexadecimal $1 = binary $(hex2bin $1)"
echo "hexadecimal $1 = octal $(hex2oct $1)"
echo "hexadecimal $1 = decimal $(hex2dec $1)"
echo "hexadecimal $1 = base32 $(hex2b32 $1)"
echo "hexadecimal $1 = base64 $(hex2b64 $1)"
echo "hexadecimal $1 = ascii $(hex2asc $1)"
fi
}
###### convert hexadecimal numbers - hex2asc
function hex2asc() {
if [[ $1 ]]; then
echo -e "\0$(printf %o $((16#$1)))"
fi
}
###### convert hexadecimal numbers - hex2bin
function hex2bin() {
if [[ $1 ]]; then
echo "obase=2 ; ibase=16 ; $1" | bc
fi
}
###### convert hexadecimal numbers - hex2b64
function hex2b64() {
if [[ $1 ]]; then
echo "obase=64 ; ibase=16 ; $1" | bc
fi
}
###### convert hexadecimal numbers - hex2b32
function hex2b32() {
if [[ $1 ]]; then
echo "obase=32 ; ibase=16 ; $1" | bc
fi
}
###### convert hexadecimal numbers - hex2dec
function hex2dec() {
if [[ $1 ]]; then
echo $((16#$1))
fi
}
###### convert hexadecimal numbers -
function hex2oct() {
if [[ $1 ]]; then
echo "obase=8 ; ibase=16 ; $1" | bc
fi
}
###### length
function length()
{
if [ $# -lt 1 ]; then
echo "count # of chars in arugment"
echo "usage: length [string]"
else
echo -n $@ | wc -c
fi
}
###### finding logs for numbers
function math-log()
{
echo "Enter value: "
read x
echo "Natural Log: ln($x) :"
echo "l($x)" | bc -l
echo "Ten Base Log: log($x) :"
echo "l($x)/l(10)" | bc -l
}
###### magic square generator (odd-order squares only!)
function msquare()
{
# Author: mendel cooper
EVEN=2
MAXSIZE=31 # 31 rows x 31 cols.
E_usage=90 # Invocation error.
dimension=
declare -i square
function usage_message()
{
echo "Usage: $0 square-size"
echo " ... where \"square-size\" is an ODD integer"
echo " in the range 3 - 31." # Works for squares up to order 159
}
function calculate() # Here's where the actual work gets done.
{
local row col index dimadj j k cell_val=1
dimension=$1
let "dimadj = $dimension * 3"; let "dimadj /= 2" # x 1.5, then truncate.
for ((j=0; j < dimension; j++))
do
for ((k=0; k < dimension; k++))
do # Calculate indices, then convert to 1-dim. array index.
# Bash doesn't support multidimensional arrays. Pity.
let "col = $k - $j + $dimadj"; let "col %= $dimension"
let "row = $j * 2 - $k + $dimension"; let "row %= $dimension"
let "index = $row*($dimension) + $col"
square[$index]=cell_val; ((cell_val++))
done
done
} # Plain math, no visualization required.
function print_square() # Output square, one row at a time.
{
local row col idx d1
let "d1 = $dimension - 1" # Adjust for zero-indexed array.
for row in $(seq 0 $d1)
do
for col in $(seq 0 $d1)
do
let "idx = $row * $dimension + $col"
printf "%3d " "${square[idx]}"; echo -n " "
done # Displays up to 13-order neatly in 80-column term window.
echo # Newline after each row.
done
}
if [[ -z "$1" ]] || [[ "$1" -gt $MAXSIZE ]]
then
usage_message
fi
let "test_even = $1 % $EVEN"
if [ $test_even -eq 0 ]
then # Can't handle even-order squares.
usage_message
fi
calculate $1
print_square # echo "${square[@]}" # DEBUG
}
###### print multiplication tables
function multitables()
{
for i in {1..9}; do for j in `seq 1 $i`; do echo -ne "${j}x${i}=$((j*i))\t"; done; echo; done
}
###### given a number, show it with comma separated values
function nicenumber()
{
# expects DD and TD to be instantiated. instantiates nicenum
# or, if a second arg is specified, the output is echoed to stdout
function nice_number()
{
# Note that we use the '.' as the decimal separator for parsing
# the INPUT value to this script. The output value is as specified
# by the user with the -d flag, if different from a '.'
integer=$(echo $1 | cut -d. -f1) # left of the decimal
decimal=$(echo $1 | cut -d. -f2) # right of the decimal
if [ $decimal != $1 ]; then
# there's a fractional part, let's include it.
result="${DD:="."}$decimal"
fi
thousands=$integer
while [ $thousands -gt 999 ]; do
remainder=$(($thousands % 1000)) # three least significant digits
while [ ${#remainder} -lt 3 ] ; do # force leading zeroes as needed
remainder="0$remainder"
done
thousands=$(($thousands / 1000)) # to left of remainder, if any
result="${TD:=","}${remainder}${result}" # builds right-to-left
done
nicenum="${thousands}${result}"
if [ ! -z $2 ] ; then
echo $nicenum
fi
}
DD="." # decimal point delimiter, between integer & fractional value
TD="," # thousands delimiter, separates every three digits
while getopts "d:t:" opt; do
case $opt in
d ) DD="$OPTARG" ;;
t ) TD="$OPTARG" ;;
esac
done
shift $(($OPTIND - 1))
if [ $# -eq 0 ] ; then
cat << "EOF" >&2
Usage: $(basename $0) [-d c] [-t c] numeric value
-d specifies the decimal point delimiter (default '.')
-t specifies the thousands delimiter (default ',')
EOF
fi
nice_number $1 1 # second arg forces this to 'echo' output
}
###### convert normal to unix
function normal2unix()
{
echo "${@}" | awk '{print mktime($0)}';
}
###### convert unix to normal
function unix2normal()
{
echo $1 | awk '{print strftime("%Y-%m-%d %H:%M:%S",$1)}';
}
###### list of numbers with equal width
function nseq()
{
seq -w 0 "$1"
}
###### convert octals - oct2all
function oct2all() {
if [[ $1 ]]; then
echo "octal $1 = binary $(oct2bin $1)"
echo "octal $1 = decimal $(oct2dec $1)"
echo "octal $1 = hexadecimal $(oct2hex $1)"
echo "octal $1 = base32 $(oct2b32 $1)"
echo "octal $1 = base64 $(oct2b64 $1)"
echo "octal $1 = ascii $(oct2asc $1)"
fi
}
###### convert octals - oct2asc
function oct2asc() {
if [[ $1 ]]; then
echo -e "\0$(printf %o $((8#$1)))"
fi
}
###### convert octals - oct2bin
function oct2bin() {
if [[ $1 ]]; then
echo "obase=2 ; ibase=8 ; $1" | bc
fi
}
###### convert octals - oct2b64
function oct2b64() {
if [[ $1 ]]; then
echo "obase=64 ; ibase=8 ; $1" | bc
fi
}
###### convert octals - oct2b32
function oct2b32() {
if [[ $1 ]]; then
echo "obase=32 ; ibase=8 ; $1" | bc
fi
}
###### convert octals - oct2dec
function oct2dec() {
if [[ $1 ]]; then
echo $((8#$1))
fi
}
###### convert octals - oct2hex
function oct2hex() {
if [[ $1 ]]; then
echo "obase=16 ; ibase=8 ; $1" | bc
fi
}
###### Pascal's triangle
function pascal() { l=15;for((i=0;i<$l;i++));do eval "a$i=($(pv=1;v=1;for((j=0;j<$l-$i;j++));do [ $i -eq 0 -o $j -eq 0 ]&&{ v=1 && pv=1; }||v=$((pv+a$((i-1))[$((j))]));echo -n "$v ";pv=$v;done;));";o="$(eval echo "$(for((k=0;k<=$i;k++)); do eval "echo -n \"\$((a\$((i-k))[k])) \""; done)")";echo "$o";s="${#o}"; done; } | while read l; do j=$((s-${#l}/2)); echo "$(while ((i++ < j)); do echo -n " ";done;)$l";done
###### convert phone numbers to letters/potentially english words
function phone2text()
{
echo -n "Enter number: "
read num
# Create a list of possibilites for expansion by the shell
# the "\}" is an ugly hack to get "}" into the replacment string -
# this is not a clean escape sequence - the litteral "\" is left behind!
num="${num//2/{a,b,c\}}"
num="${num//3/{d,e,f\}}"
num="${num//4/{g,h,i\}}"
num="${num//5/{j,k,l\}}"
num="${num//6/{m,n,o\}}"
num="${num//7/{p,q,r,s\}}"
num="${num//8/{t,u,v\}}"
num="${num//9/{w,x,y,z\}}"
# cleaup from the hack - remove all litteral \'s
num="${num//\\/}"
echo ""
echo "Possible words are:"
for word in $( eval echo "$num" )
do
echo '>' "$word"
done
# End of File
}
###### powers of numerals
function power() {
if [[ $1 ]]; then
if [[ $2 ]]; then
echo "$1 ^ $2" | bc
else echo "$1 ^ 2" | bc
fi
fi
}
###### generate prime numbers, without using arrays.
function primes()
{
LIMIT=1000 # Primes, 2 ... 1000.
Primes()
{
(( n = $1 + 1 )) # Bump to next integer.
shift # Next parameter in list.
# echo "_n=$n i=$i_"
if (( n == LIMIT ))
then echo $*
return
fi
for i; do # "i" set to "@", previous values of $n.
# echo "-n=$n i=$i-"
(( i * i > n )) && break # Optimization.
(( n % i )) && continue # Sift out non-primes using modulo operator.
Primes $n $@ # Recursion inside loop.
return
done
Primes $n $@ $n # Recursion outside loop.
# Successively accumulate
#+ positional parameters.
# "$@" is the accumulating list of primes.
}
Primes 1
}
###### radicals of numbers
function radical() {
if [[ $1 ]]; then
echo "sqrt($1)" | bc -l
fi
}
###### convert to roman numerals
function roman-numeral()
{
python -c 'while True: print (lambda y,x=[],nums={ 1000:"M",900:"CM",500:"D",400:"CD",100:"C",90:"XC",
50:"L",40:"XL",10:"X",9:"IX",5:"V",4:"IV",1:"I"}: (lambda ro=(lambda : map(lambda g,r=lambda b:x.append(
y[-1]/b),t=lambda v:y.append(y[-1]%v):map(eval,["r(g)","t(g)"]),sorted(nums.keys())[::-1]))():"".join(
map(lambda fg: map(lambda ht: nums[ht],sorted(nums.keys())[::-1])[fg] * x[fg],range(len(x)))))())([int(
raw_input("Please enter a number between 1 and 4000: "))])'
}
###### round numerals to whole numbers
function round() {
if [[ $1 ]]; then
if [[ $2 ]]; then
echo "$(printf %.${2}f $1)"
else echo "$(printf %.0f $1)"
fi
fi
}
###### ruler that stretches across the terminal
function ruler() { for s in '....^....|' '1234567890'; do w=${#s}; str=$( for (( i=1; $i<=$(( ($COLUMNS + $w) / $w )) ; i=$i+1 )); do echo -n $s; done ); str=$(echo $str | cut -c -$COLUMNS) ; echo $str; done; }
###### convert seconds to minutes, hours, days, and etc. - inputs a number of seconds, outputs a string like "2 minutes, 1 second" $1: number of seconds
function sec2all()
{
local millennia=$((0))
local centuries=$((0))
local years=$((0))
local days=$((0))
local hour=$((0))
local mins=$((0))
local secs=$1
local text=""
# convert seconds to days, hours, etc
millennia=$((secs / 31536000000))
secs=$((secs % 31536000000))
centuries=$((secs / 3153600000))
secs=$((secs % 3153600000))
years=$((secs / 31536000))
secs=$((secs % 31536000))
days=$((secs / 86400))
secs=$((secs % 86400))
hour=$((secs / 3600))
secs=$((secs % 3600))
mins=$((secs / 60))
secs=$((secs % 60))
# build full string from unit strings
text="$text$(seconds-convert-part $millennia "millennia")"
text="$text$(seconds-convert-part $centuries "century")"
text="$text$(seconds-convert-part $years "year")"
text="$text$(seconds-convert-part $days "day")"
text="$text$(seconds-convert-part $hour "hour")"
text="$text$(seconds-convert-part $mins "minute")"
text="$text$(seconds-convert-part $secs "second")"
# trim leading and trailing whitespace
text=${text## }
text=${text%% }
# special case for zero seconds
if [ "$text" == "" ]; then
text="0 seconds"
fi
# echo output for the caller
echo ${text}
}
# formats a time unit into a string - $1: integer count of units: 0, 6, etc - $2: unit name: "hour", "minute", etc
function seconds-convert-part()
{
local unit=$1
local name=$2
if [ $unit -ge 2 ]; then
echo " ${unit} ${name}s"
elif [ $unit -ge 1 ]; then
echo " ${unit} ${name}"
else
echo ""
fi
}
###### finding the square root of numbers
function sqrt()
{
echo "sqrt ("$1")" | bc -l
}
###### converts a string (words, text) to binary
function string2bin()
{
perl -nle 'printf "%0*v8b\n"," ",$_'
}
###### trigonmetry calculations with angles
function trig-angle()
{
echo "Enter angle in degree: "
read deg
# Note: Pi calculation
# tan(pi/4) = 1
# atan(1) = pi/4 and
# pi = 4*atan(1)
pi=`echo "4*a(1)" | bc -l`
rad=`echo "$deg*($pi/180)" | bc -l`
echo "$deg Degree = $rad Radian"
echo "Sin($deg): "
echo "s($rad)" | bc -l
echo "Cos($deg): "
echo "c($rad)" | bc -l
echo "Tan($deg): "
echo "s($rad)/c($rad)" | bc -l
}
####### Ask
function ask()
{
echo -n "$@" '[y/n] ' ; read ans
case "$ans" in
y*|Y*) return 0 ;;
*) return 1 ;;
esac
}
######## Escape potential tarbombs
function atb() { l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.tar.gz} && tar xf $1 -C ${1%.tar.gz}; fi ; }
######### Get the headlines of an atom feed
function atomtitles()
{
curl --silent $1 | xmlstarlet sel -N atom="http://www.w3.org/2005/Atom" -t -m /atom:feed/atom:entry -v atom:title -n
}
####### backupsfolder
function backupsfolder()
{
if [ -d $HOME/backups_html ]; then
chown -R $USER:www-data $HOME/backups_html
chmod 755 $HOME/backups_html
find $HOME/backups_html/ -type d -exec chmod 775 {} \;
find $HOME/backups_html/ -type f -exec chmod 664 {} \;
chmod 755 $HOME
fi
}
####### private
function private()
{
find $HOME -type d -exec chmod 700 {} \;
find $HOME -type f -exec chmod 600 {} \;
find $HOME/bin -type f -exec chmod +x {} \;
find $HOME/.dropbox-dist/dropbox* -type f -exec chmod +x {} \;
}
####### publicfolder
function publicfolder()
{
if [ -d $HOME/public_html ]; then
chown -R $USER:www-data $HOME/public_html
chmod 755 $HOME/public_html
find $HOME/public_html/ -type d -exec chmod 775 {} \;
find $HOME/public_html/ -type f -exec chmod 664 {} \;
chmod 755 $HOME
fi
}
####### setperms
function setperms()
{
echo "setting proper permissions in ~/"
private
public
}
####### wwwrc
function wwwrc()
{
alias mv="mv"
mv -f ~/.[a-z]*.html ~/public_html/
chmod 644 ~/public_html/.[a-z]*.html
chown $USER:www-data ~/public_html/.[a-z]*.html
alias mv="mv -i"
}
####### Backup .bash* files
function backup_bashfiles()
{
ARCHIVE="$HOME/bash_dotfiles_$(date +%Y%m%d_%H%M%S).tar.gz";
cd ~
tar -czvf $ARCHIVE .bash_profile .bashrc .bash_functions .bash_aliases .bash_prompt
echo "All backed up in $ARCHIVE";
}
####### Creates a backup of the file passed as parameter with the date and time
function bak()
{
cp $1 $1_`date +%H:%M:%S_%d-%m-%Y`
}
####### Good bash tips for everyone
function bashtips() {
cat <<EOF
DIRECTORIES
-----------
~- Previous working directory
pushd tmp Push tmp && cd tmp
popd Pop && cd
GLOBBING AND OUTPUT SUBSTITUTION
--------------------------------
ls a[b-dx]e Globs abe, ace, ade, axe
ls a{c,bl}e Globs ace, able
\$(ls) \`ls\` (but nestable!)
HISTORY MANIPULATION
--------------------
!! Last command
!?foo Last command containing \`foo'
^foo^bar^ Last command containing \`foo', but substitute \`bar'
!!:0 Last command word
!!:^ Last command's first argument
!\$ Last command's last argument
!!:* Last command's arguments
!!:x-y Arguments x to y of last command
C-s search forwards in history
C-r search backwards in history
LINE EDITING
------------
M-d kill to end of word
C-w kill to beginning of word
C-k kill to end of line
C-u kill to beginning of line
M-r revert all modifications to current line
C-] search forwards in line
M-C-] search backwards in line
C-t transpose characters
M-t transpose words
M-u uppercase word
M-l lowercase word
M-c capitalize word
COMPLETION
----------
M-/ complete filename
M-~ complete user name
M-@ complete host name
M-\$ complete variable name
M-! complete command name
M-^ complete history
EOF
}
###### # Execute a given Linux command on a group of files - Example1: batchexec sh ls # lists all files that have the extension 'sh' - Example2: batchexec sh chmod 755 # 'chmod 755' all files that have the extension 'sh'
function batchexec()
{
find . -type f -iname '*.'${1}'' -exec ${@:2} {} \; ;
}
# Clock - A bash clock that can run in your terminal window.
#------------------------------------------////
###### binary clock
function bclock()
{
watch -n 1 'echo "obase=2;`date +%s`" | bc'
}
###### binary clock
function bclock2()
{
perl -e 'for(;;){@d=split("",`date +%H%M%S`);print"\r";for(0..5){printf"%.4b ",$d[$_]}sleep 1}'
}
###### clock
function clock()
{
while true;do clear;echo "===========";date +"%r";echo "===========";sleep 1;done
}
###### Appends a '&' to a command so it will run in the background - useful for aliases
function bg_wrapper()
{
"$@" &
}
####### Substitutes underscores for blanks in all the - filenames in a directory
function blank_rename()
{
ONE=1 # For getting singular/plural right (see below).
number=0 # Keeps track of how many files actually renamed.
FOUND=0 # Successful return value.
for filename in * #Traverse all files in directory.
do
echo "$filename" | grep -q " " # Check whether filename
if [ $? -eq $FOUND ] #+ contains space(s).
then
fname=$filename # Yes, this filename needs work.
n=`echo $fname | sed -e "s/ /_/g"` # Substitute underscore for blank.
mv "$fname" "$n" # Do the actual renaming.
let "number += 1"
fi
done
if [ "$number" -eq "$ONE" ] # For correct grammar.
then
echo "$number file renamed."
else
echo "$number files renamed."
fi
}
####### Convert bluray to xvid # example: bluray2xvid bluraydisc.m2ts desired_name.avi
function bluray2xvid()
{
mencoder $1 -oac mp3lame -lameopts cbr:br=128 -ofps 24 -vf harddup -vf scale=1280:720 -ovc xvid -xvidencopts fixed_quant=3 -o $2
}
# Bookmarking
#------------------------------------------////
###### bookmarking the current directory in 'alias' form
function bookmark() {
if [[ $1 != "" && $(alias | grep -w go-$1) == "" ]]; then
echo "alias go-$1='cd $PWD'" >> $HOME/.bookmarks
. $HOME/.bookmarks
elif [[ $1 == "" ]]; then
echo "need name for the bookmark."
else echo "bookmark go-$1 already exists."
fi
}
###### unmark
function unmark() {
if [[ $(alias | grep -w go-$1= ) != "" ]]; then
sed -e "/go-$1/d" -i $HOME/.bookmarks
xunalias go-$1
fi
}
###### copies files to a bookmarked dir - cto file1.jpg file2.jpg file3.jpg pics
function cto() {
eval lastarg=\${$#}
targetdir=`getBookmark $lastarg`
echo "Copying files to $targetdir"
if [ -n "$targetdir" ]; then
for dir in "$@";
do
if [ "$dir" != $lastarg ]; then
cp -iv "$dir" "$targetdir"
fi
done
fi
}
###### moves files to a bookmarked dir - mto vid1.avi vid2.avi videos
function mto() {
eval lastarg=\${$#}
targetdir=`getBookmark $lastarg`
echo "Moving files to $targetdir"
if [ -n "$targetdir" ]; then
for dir in "$@";
do
if [ "$dir" != $lastarg ]; then
mv -iv "$dir" "$targetdir"
fi
done
fi
}
###### Directory Bookmarks for BASH (c) 2009, Ira Chayut, Version 090927
# DirB and its implementation in this file are the product of, and
# copyrighted by Ira Chayut. You are granted a non-exclusive, royalty-free
# license to use, reproduce, modify and create derivative works from DirB;
# providing that credit is given to DirB as a source material.
# The lastest version is available from: http://www.dirb.info/bashDirB. Ira can
# be reached at [email protected].
# By default DirB will have the shell echo the current working directory out
# to the title bars of Xterm windows. To disable this behavior, comment
# out the next line.
# PS1="\[\033]0;\w\007\]\t \!> "
# If the repository of bookmarks does not exist, create it
if [ ! -e ~/.DirB ]
then
mkdir ~/.DirB
fi
###### "d" - Display (or Dereference) a saved bookmark - to use: cd "$(d xxx)"
function d() {
# if the bookmark exists, then extract its directory path and print it
if [ -e ~/.DirB/"$1" ]
then
sed -e 's/\$CD //' -e 's/\\//g' ~/.DirB/"$1"
# if the bookmark does not exists, complain and exit with a failing code
else
echo bash: DirB: ~/.DirB/"$1" does not exist >&2
false
fi
}
###### "g" - Go to bookmark
function g() {
# if no arguments, then just go to the home directory
if [ -z "$1" ]
then
cd
else
# if $1 is in ~/.DirB and does not begin with ".", then go to it
if [ -f ~/.DirB/"$1" -a ${1:0:1} != "." ]
then
# update the bookmark's timestamp and then execute it
touch ~/.DirB/"$1" ;
CD=cd source ~/.DirB/"$1" ;
# else just do a "cd" to the argument, usually a directory path of "-"
else
cd "$1"
fi
fi
}
###### "p" - Push a bookmark
function p() {
# Note, the author's preference is to list the directory stack in a single
# column. Thus, the standard behavior of "pushd" and "popd" have been
# replaced by discarding the normal output of these commands and using a
# "dirs -p" after each one.
# if no argument given, then just pushd and print out the directory stack
if [ -z "$1" ]
then
pushd > /dev/null && dirs -p
# if $1 is a dash, then just do a "popd" and print out the directory stack
elif [ "$1" == "-" ]
then
popd > /dev/null
dirs -p
else
# if $1 is in ~/.DirB and does not begin with ".", then go to it
# and then print out the directory stack
if [ -f ~/.DirB/"$1" -a "${1:0:1}" != "." ]
then
touch ~/.DirB/$1 ;
CD=pushd source ~/.DirB/$1 > /dev/null && dirs -p ;
# else just do a "pushd" and print out the directory stack
else
pushd "$1" > /dev/null && dirs -p
fi
fi
}
###### "r" - Remove a saved bookmark
function r() {
# if the bookmark file exists, remove it
if [ -e ~/.DirB/"$1" ]
then
rm ~/.DirB/"$1"
# if the bookmark file does not exist, complain and exit with a failing code
else
echo bash: DirB: ~/.DirB/"$1" does not exist >&2
false
fi
}
###### "s" - Save bookmark
function s() {
if [ -n "$2" ]
then
# build the bookmark file with the contents "$CD directory_path"
( echo '$CD ' \"$2\" > ~/.DirB/"$1" ;) > /dev/null 2>&1
else
# build the bookmark file with the contents "$CD directory_path"
( echo -n '$CD ' > ~/.DirB/"$1" ;
pwd | sed "s/ /\\\\ /g" >> ~/.DirB/"$1" ; ) > /dev/null 2>&1
fi
# if the bookmark could not be created, print an error message and
# exit with a failing return code
if [ $? != 0 ]
then
echo bash: DirB: ~/.DirB/"$1" could not be created >&2
false
fi
}
###### "sl" - Saved bookmark Listing
function sl() {
# if the "-l" argument is given, then do a long listing, passing any
# remaining arguments to "ls", printing in reverse time order. Pass the
# output to "less" to page the output if longer than a screen in length.
if [ "$1" == "-l" ]
then
shift
( cd ~/.DirB ;
ls -lt $* |
sed -e 's/ */ /g' -e '/^total/d' \
-e 's/^\(... \)\([0-9] \)/\1 \2/' |
cut -d ' ' -s -f6- | sed -e '/ [0-9] /s// &/' | less -FX ; )
# else print the short form of the bookmarks in reverse time order
else
( cd ~/.DirB ; ls -xt $* ; )
fi
}
###### simple bookmark system
function getBookmark() {
case "$1" in
video|vids|vid) echo "~/Videos" ;; # video, vids and vid are shortcuts to use with the functions below, the bookmarked directory is "~/videos"
images|img|pics|pictures) echo "~/Pictures";;
*) echo "" ;;
esac
}
###### list contents of a bookmarked dir without - going there: list vids
function list() {
dir=`getBookmark $1`
echo $dir
if [ -n "$dir" ]; then
ls "$dir"
fi
}
###### same as "list" but with details: llist vids
function llist() {
dir=`getBookmark $1`
echo $dir
if [ -n "$dir" ]; then
ll "$dir"
fi
}
###### Create box of '#' characters around given string
function box() { t="$1xxxx";c=${2:-#}; echo ${t//?/$c}; echo "$c $1 $c"; echo ${t//?/$c}; }
# Download all videos in your Boxee queue Gets all videos in your boxee queue with a URL associated with them and attempts to download each using get_flash_videos
function boxeedl()
{
for i in $(curl -u <username> http://app.boxee.tv/api/get_queue | xml2 | grep /boxeefeed/message/object/url | cut -d "=" -f 2,3); do get_flash_videos $i; done
}
# Randomness #
#------------------------------------------////
###### This script models Brownian motion: random wanderings of tiny particles in fluid, as they are buffeted by random currents and collisions (colloquially known as "Drunkard's Walk")
function brownian()
{
PASSES=500 # Number of particle interactions / marbles.
ROWS=10 # Number of "collisions" (or horiz. peg rows).
RANGE=3 # 0 - 2 output range from $RANDOM.
POS=0 # Left/right position.
RANDOM=$$ # Seeds the random number generator from PID of script.
declare -a Slots # Array holding cumulative results of passes.
NUMSLOTS=21 # Number of slots at bottom of board.
function Initialize_Slots() { # Zero out all elements of the array.
for i in $( seq $NUMSLOTS )
do
Slots[$i]=0
done
echo # Blank line at beginning of run.
}
function Show_Slots() {
echo -n " "
for i in $( seq $NUMSLOTS ) # Pretty-print array elements.
do
printf "%3d" ${Slots[$i]} # Allot three spaces per result.
done
echo # Row of slots:
echo " |__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|"
echo " ^^"
echo # Note that if the count within any particular slot exceeds 99,
#+ it messes up the display.
# Running only(!) 500 passes usually avoids this.
}
function Move() { # Move one unit right / left, or stay put.
Move=$RANDOM # How random is $RANDOM? Well, let's see ...
let "Move %= RANGE" # Normalize into range of 0 - 2.
case "$Move" in
0 ) ;; # Do nothing, i.e., stay in place.
1 ) ((POS--));; # Left.
2 ) ((POS++));; # Right.
* ) echo -n "Error ";; # Anomaly! (Should never occur.)
esac
}
function Play() { # Single pass (inner loop).
i=0
while [ "$i" -lt "$ROWS" ] # One event per row.
do
Move
((i++));
done
SHIFT=11 # Why 11, and not 10?
let "POS += $SHIFT" # Shift "zero position" to center.
(( Slots[$POS]++ )) # DEBUG: echo $POS
}
function Run() { # Outer loop.
p=0
while [ "$p" -lt "$PASSES" ]
do
Play
(( p++ ))
POS=0 # Reset to zero. Why?
done
}
# main()
Initialize_Slots
Run
Show_Slots
}
###### flip a single coin 1000 times and show results
function coin-flip()
{
SEED=$"(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')"
RANDOM=$SEED
SIDES=2 # A coin has 2 sides.
MAXTHROWS=1000 # Increase this if you have nothing better to do with your time.
throw=0 # Throw count.
heads=0 # Must initialize counts to zero,
tails=0 # since an uninitialized variable is null, not zero.
function print_result()
{
echo
echo "heads = $heads"
echo "tails = $tails"
echo
}
function update_count()
{
case "$1" in
0) let "heads += 1";; # Since coin has no "zero", this corresponds to 1.
1) let "tails += 1";; # And this to 2, etc.
esac
}
echo
while [ "$throw" -lt "$MAXTHROWS" ]
do
let "coin1 = RANDOM % $SIDES"
update_count $coin1
let "throw += 1"
done
print_result
echo "Out of a total of "$MAXTHROWS" tosses."
echo "Change \"MAXTHROWS=1000\" if you want a different number of tosses."
}
###### roll a single die of "$1" sides, just once default number of sides is 6
function one-die()
{
function roll_die() {
# capture parameter
declare -i DIE_SIDES=$1
# check for die sides
if [ ! $DIE_SIDES -gt 0 ]; then
# default to 6
DIE_SIDES=6
fi
# echo to screen
echo $[ ( $RANDOM % $DIE_SIDES ) + 1 ]
}
# roll_die 10 # returns 1 to 10 as per 10 sides
# roll_die 2 # returns 1 or 2 as per 2 sides
roll_die "$1"
}
###### select random card from a deck
function pick-card()
{
# This is an example of choosing random elements of an array.
# Pick a card, any card.
Suites="Clubs
Diamonds
Hearts
Spades"
Denominations="2
3
4
5
6
7
8
9
10
Jack
Queen
King
Ace"
# Note variables spread over multiple lines.
suite=($Suites) # Read into array variable.
denomination=($Denominations)
num_suites=${#suite[*]} # Count how many elements.
num_denominations=${#denomination[*]}
echo -n "${denomination[$((RANDOM%num_denominations))]} of "
echo ${suite[$((RANDOM%num_suites))]}
# $bozo sh pick-cards.sh
# Jack of Clubs
# Thank you, "jipe," for pointing out this use of $RANDOM.
}
###### random number (out of whatever you input) example: random 10 = 4
function random() {
if [[ $1 == -l ]]; then
echo $(cat /dev/urandom | tr -cd '[:digit:]' | head -c ${2-5})
elif [[ $1 == -r ]]; then
echo $((RANDOM%${2}))
else echo $((RANDOM%${1}))
fi
}
###### create random blank files
function randomblanks()
{
for (( i = 0 ; i < $1; i++ )); do touch $RANDOM; done
}
###### random file
function randomfile() {
case $1 in
*first)
sed -n '1p' $HOME/.randomhistory
;;
*last)
sed -n '$p' $HOME/.randomhistory
;;
*n)
sed -n "${2}p" $HOME/.randomhistory
;;
*l)
wc -l $HOME/.randomhistory | gawk '{print $1}'
;;
*c)
rm $HOME/.randomhistory
;;
*help )
echo -e "\n${ewhite}Usage:\n"
echo -e "${eorange}randomfile${ewhite} | ${egreen}--first ${eiceblue}[get the first file in the history]\
\n${eorange}randomfile${ewhite} | ${egreen}--last ${eiceblue}[get the last file in the history]\
\n${eorange}randomfile${ewhite} | ${egreen}--n ${eiceblue}[get the NUMBERth file in the history]\
\n${eorange}randomfile${ewhite} | ${egreen}--l ${eiceblue}[get the number of files in history]\
\n${eorange}randomfile${ewhite} | ${egreen}--c ${eiceblue}[clear the history]\n" | column -t
tput sgr0
;;
*)
if [[ ! "$FILES" ]]; then
files=(*)
else files=("$FILES")
fi
n=${#files[@]}
RANDOMFILE="${files[RANDOM % n]}"
echo "$RANDOMFILE" >> $HOME/.randomhistory
if [[ ! "$@" ]]; then
echo "$RANDOMFILE"
else "$@" "$RANDOMFILE"
fi
;;
esac
}
###### pulls a random line from text file
function randomline()
{
# AUTHOR: David Ivan Stark (clyphox), [email protected]
if [ "$1" ];then #checking if we were passed a filename/variable
FileName="$1" #just an easier variable to work with
if [ ! -f "$FileName" ];then #check if it is a file
echo "Err: $FileName is not a file"
fi
#Count how many lines in the file
LineCount="$(wc -l "$FileName" | cut -f 1 -d ' ')"
#Dont continue if we have less than 1 line
if [ "$LineCount" -gt "1" ];then
#Test past.. selecting random line
TargetLine=$[ ( $RANDOM % $LineCount ) + 1 ]
Output="$(sed -n "${TargetLine}p" "$FileName")"
echo "$Output"
else
echo need a file with more than 1 line... cmon...
fi
else #seems we didnt get any input
echo "Please specify a text file"
fi
}
###### Generates neverending list of random numbers
function randomnumbers()
{
while :
do
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
done
}
###### Random wallpaper (add whatever wallpaper directory(s) you wish after 'BACKGROUND_DIRS')
# function randomwp()
# # for GNOME2
# {
# cat > "/tmp/randomwp.py" <<"End-of-message"
# #!/usr/bin/env python
# BACKGROUND_DIRS = ['/usr/share/backgrounds', '~/Pictures/Backgrounds']
# EXTENSIONS = ['jpeg', 'jpg', 'bmp', 'png', 'svg']
# import os, glob, random, itertools, gconf
# files = list(itertools.chain(*[[os.path.join(dirpath, name)
# for name in filenames]
# for dirpath, dirnames, filenames in
# itertools.chain(*[os.walk(os.path.expanduser(d))
# for d in BACKGROUND_DIRS])]))
# gconf.client_get_default().set_string(
# '/desktop/gnome/background/picture_filename',
# random.choice(files))
# End-of-message
# chmod +x "/tmp/randomwp.py"
# "/tmp/randomwp.py"
# /bin/rm "/tmp/randomwp.py"
# }
###### Random-Gnome3-Wallpaper.sh - for GNOME3 Script to randomly set desktop/gdm background - Requires: sudo-apt get install randomize-lines
function randomwp()
{
###### just add/remove as many directories as wish
find "/usr/share/backgrounds" "$HOME/Pictures/Backgrounds" -type f \( -name "*.bmp" -or -name "*.BMP" -or -name "*.jpeg" -or -name "*.JPEG" -or -name "*.jpg" -or -name "*.JPG" -or -name "*.png" -or -name "*.PNG" -or -name "*.svg" -or -name "*.SVG" \)|rl|head -n 1|xargs -I{} bash -c "gsettings set org.gnome.desktop.background picture-uri \"file://{}\""
}
###### Random-Gnome3-Wallpaper-2.sh - Script to randomly set desktop/gdm background
function randomwp_()
{
###### Directories Containing Pictures (to add more folders here, just "/path/to/your/folder")
arr[0]="/usr/share/backgrounds"
arr[1]="$HOME/Pictures/Backgrounds"
# arr[2]=
# arr[3]=
# arr[4]=
# arr[5]=
# arr[6]=
# arr[7]=
# arr[8]=
# arr[9]=
# arr[10]=
###### How many picture folders are there? (currently = 2)
rand=$[ $RANDOM % 2 ]
###### Command to select a random folder
DIR=`echo ${arr[$rand]}`
###### Command to select a random file from directory
# The *.* should select only files (ideally, pictures, if that's all that's inside)
PIC=$(ls $DIR/*.* | shuf -n1)
###### Command to set background Image
gsettings set org.gnome.desktop.background picture-uri "file://$PIC"
}
###### randomwpt automatic wallpaper switcher for GNOME2 - Usage: randomwpt "bash directory_name" "timeout_in_seconds" - for GNOME2 only
function randomwpt()
{
if [ $# -ne 2 ];then
echo -n "Usage: $0 directory_name timeout_in_seconds
Leave the directory name blank for Current Directory
For you lazy pal, I assume timeout as 5 sec and Directory as current
Do you want to accept this settings? (Y/n): ";
read response
if [[ "$response" =~ ^[^yY] ]];then
exit 0
fi
fi
function set_wallpaper() {
gconftool-2 -s /desktop/gnome/background/picture_options "centered" -t string;
gconftool-2 -s /desktop/gnome/background/picture_filename "$1" -t string;
}
TIMEOUT=${2-5};
WALL_DIR=${1-`pwd`};
echo "Timeout value is: $TIMEOUT";
echo "Directory is: $WALL_DIR";
echo
if [ ! -d "$WALL_DIR" ];then
echo "The Directory Specified is invalid..";
exit 1;
fi
filelst="$(find "$WALL_DIR" -type f -name '*.jpg' -o -name '*.png')";
if [ -z "$filelst" ];then
echo "No Suitable files found in this location: $WALL_DIR";
exit 1;
fi
while true;do
filename=`echo "$filelst" | shuf -n 1`
set_wallpaper "$filename";
sleep $TIMEOUT;
done
}
###### rename a file with a random name The function will rename files but maintain their extensions. BUG: If a file doesn't have an extension it will end up with a dot at the end of the name. The parameter '8' for pwgen controls the length of filenames - eight random characters.
function rf() { for i in "$@"; do mv "$i" "$(pwgen 8 1).${i##*.}"; done }
###### roll a single die 1000 times and show results
function roll-die()
{
SEED=$"(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')"
RANDOM=$SEED
PIPS=6 # A die has 6 pips.
MAXTHROWS=1000 # Increase this if you have nothing better to do with your time.
throw=0 # Throw count.
ones=0 # Must initialize counts to zero,
twos=0 #+ since an uninitialized variable is null, not zero.
threes=0
fours=0
fives=0
sixes=0
function print_result()
{
echo
echo "ones = $ones"
echo "twos = $twos"
echo "threes = $threes"
echo "fours = $fours"
echo "fives = $fives"
echo "sixes = $sixes"
echo