bash:functions:my_functions
BASH - Functions - My Functions
- /etc/profile.d/bash_functions.sh
#------------------------------------------------------------- # 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 <<End-Of-Usage Usage: ${FUNCNAME[0]} [option] <archives> 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 ;; esac 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) tar "xvJf" "$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) unxz "$1" ;; *.xz) xz --decompress "$1" ;; *.zip|*.war|*.jar) unzip "$1" ;; *.Z) uncompress "$1" ;; # *.7z) 7za x "$1" ;; *.7z) 7z x "$1" ;; *.arj|*.cab|*.chm|*.dmg|*.iso|*.lzh|*.msi|*.udf|*.wim|*.xar) 7z x "$1" ;; ## *.deb|*.rpm *) 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" ; } #------------------------------------------------------------- # Backup functions. #------------------------------------------------------------- # Copy a file to the current directory with today’s date automatically appended to the end. # Usage: bu filename.txt bu() { cp “$1” “$1”.backup-`date +%H%M%S_%y%m%d`; } #------------------------------------------------------------- # Calculator functions. #------------------------------------------------------------- # Calculate an expression e.g. calc 1+1. calc() { echo "$@"|bc -l; # 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' ' -f11` 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. #------------------------------------------------------------- # CHMOD _D_irectory _R_ecursivly chmoddr() { if [ -d "$1" ]; then echo "error: please use the mode first, then the directory"; return 1; elif [ -d "$2" ]; then find $2 -type d -print0 | xargs -0 chmod $1; fi } function dus () { du --max-depth=0 -k * | sort -n | awk '{ if($1>=1024*1024) {size=$1/1024/1024; unit="G"} else if($1>=1024) {size=$1/1024; unit="M"} else {size=$1; unit="K"}; if(size<10) format="%.1f%s"; else format="%.0f%s"; res=sprintf(format,size,unit); printf "%-8s %s\n",res,$2 }' } # Jumps to a directory at any level below using globstar. jd() { if [ -z $1 ]; then echo "Usage: jd [directory]"; return 1 else cd **/$@ fi } # mkdir, follow it with cd to that directory. function mkcd { if [ -n "$1" -a ! -a "$1" ] then mkdir "$1" cd "$1" else echo NO 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 } #------------------------------------------------------------- # Docker functions. #------------------------------------------------------------- function dockershellhere() { dirname=${PWD##*/} docker run --rm -it --entrypoint=/bin/bash -v `pwd`:/${dirname} -w /${dirname} "$@" } function dockershellshhere() { dirname=${PWD##*/} docker run --rm -it --entrypoint=/bin/sh -v `pwd`:/${dirname} -w /${dirname} "$@" } # Listing Docker Tags. # Example: dockertags python dockertags () { local image="${1}" wget -q https://registry.hub.docker.com/v1/repositories/"${image}"/tags -O - \ | tr -d '[]" ' | tr '}' '\n' | awk -F: '{print $3}' } # Bash into Docker container. dockerbash() { docker exec -it $@ bash; } dockersh() { docker exec -it $@ sh; } # Bash into Kubernetes Pod. kubsh() { kubectl exec -it $@ -- /bin/sh; } kubbash() { kubectl exec -it $@ -- /bin/bash; } #------------------------------------------------------------- # Downloading functions. #------------------------------------------------------------- # More persistent wget for fetching files to a specific filename. wgettofile() { [ $# -ne 2 ] && echo "usage: wgettofile <url> <filename>" && 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 "$*" peter 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 } # Count the file arguments matching the file operator # Synopsys: # count_files operator FILE [...] # Arguments: # $1: The file operator # Allowed values: # -a FILE True if file exists. # -b FILE True if file is block special. # -c FILE True if file is character special. # -d FILE True if file is a directory. # -e FILE True if file exists. # -f FILE True if file exists and is a regular file. # -g FILE True if file is set-group-id. # -h FILE True if file is a symbolic link. # -L FILE True if file is a symbolic link. # -k FILE True if file has its `sticky' bit set. # -p FILE True if file is a named pipe. # -r FILE True if file is readable by you. # -s FILE True if file exists and is not empty. # -S FILE True if file is a socket. # -t FD True if FD is opened on a terminal. # -u FILE True if the file is set-user-id. # -w FILE True if the file is writable by you. # -x FILE True if the file is executable by you. # -O FILE True if the file is effectively owned by you. # -G FILE True if the file is effectively owned by your group. # -N FILE True if the file has been modified since it was last read. # $@: The files arguments # # Output: # The number of matching files. # # Return: # 1: Unknown file operator. # # Example usages: # count_files -f log*.txt # count_files -d datadir* filecountbytype() { operator=$1 shift case $operator in -[abcdefghLkprsStuwxOGN]) for arg; do # If file is not of required type. if ! test "$operator" "$arg"; then # Shift it out. shift fi done echo $# ;; *) printf 'Invalid file operator: %s\n' "$operator" >&2 return 1 ;; esac } #filecountbytype "$@" # 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. 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 } # Check a JSON file. # usage: json file.json # If all is well, it will print the JSON file to the screen. # If there is an error in the file, the error is printed along with the offending line number. function json() { cat "$@" | /usr/bin/python -m json.tool ; } # Returns one random line from the file specified as first parameter. function fileraffle() { head -$((${RANDOM} % `wc -l < $1` + 1)) $1 | tail -1 } # Use null to zero/create a file. function touchf() { [[ $# -gt 0 ]] && cat /dev/null > "$*"; } #------------------------------------------------------------- # 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: 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 ; } #wordsall() { /bin/grep "^[$W]*$" /usr/share/dict/words ; } #wordsall() { /bin/grep "^[$@]*$" /usr/share/dict/words ; } words() { /bin/grep ^"[$@]+"$ /usr/share/dict/words ; } # Splits a word into separate letter combinations. wordc(){ combos () { local word=$1 local len=${#word} # local first=${word:0:1} # echo "$first" for ((i=1; i <= len; i++ )); do local first=${word:i-1:1} echo "$first" for ((j=1; i+j <= len; j++ )); do echo "$first${word:i:j}" done done } combos $1 } # Splits a word into separate letter permutations. wordp() { function permutate { if [ "${#1}" = 1 ]; then echo "${2}${1}" # /bin/grep ^"${2}${1}"$ /usr/share/dict/words # /bin/grep ^"${2}"$ /usr/share/dict/words # echo "${1}" # echo "${2}" else for i in $(seq 0 $((${#1}-1)) ); do pre="${2}${1:$i:1}" seg1="${1:0:$i}" seg2="${1:$((i+1))}" seg="${seg1}${seg2}" permutate "$seg" "$pre" done fi } #permutate $@ permutate $1 } # Usage: wordd cat | sort | uniq wordd(){ combos () { local word=$1 local len=${#word} #for ((i=1; i < len; i++ )); do # local first=${word:0:1} #done for ((i=0; i<=len; i++ )); do for ((j=0; j<=len; j++ )); do for ((w=1; w<=len; w++ )); do #printf "%s%s%s", chars[i], chars[j], (j<numChars ? OFS : ORS) #echo "$first${word:i:j}" local charsi=${word:i:w} local charsj=${word:j:w} if [[ $i != $j && $charsi != $charsj ]]; then echo "$charsi$charsj" fi #echo "$first${word:i:j}" done done done } combos $1 } # TODO - DETERMINE WHAT THIS IS FOR...PERHAPS DELETE. wordsx() { w="$@" sortedWord=`echo "$@" | grep -o . | sort | tr -d '\n'` echo $sortedWords while read line do sortedLine=`echo $line | grep -o . | sort | tr -d '\n'` if [ "$sortedWord" == "$sortedLine" ] then echo $line fi done < /usr/share/dict/words } #------------------------------------------------------------- # History functions. #------------------------------------------------------------- #histtop10() #{ # history | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10 #} # Returns top 10 commands used in the history. # Check alias candidates. function hist10() { history | \ awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' \ | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10 } #------------------------------------------------------------- # Image functions. #------------------------------------------------------------- # Scrape images. # Example: imagescrape https://example.com/ imagescraoe() { wget -nd -H -p -A jpg,jpeg,png,gif -e robots=off $1 } #------------------------------------------------------------- # 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" ; myip echo -e "\n${BRed}Open connections :$NC "; netstat -pan --inet; echo } function info() { printf "\n" #printf " %s\n" "IP ADDR: $(curl ifconfig.me)" printf " %s\n" "USER: $(echo $USER)" printf " %s\n" "DATE: $(date)" printf " %s\n" "UPTIME: $(uptime -p)" printf " %s\n" "HOSTNAME: $(hostname -f)" printf " %s\n" "CPU: $(awk -F: '/model name/{print $2}' | head -1)" printf " %s\n" "KERNEL: $(uname -rms)" printf " %s\n" "PACKAGES: $(dpkg --get-selections | wc -l)" printf " %s\n" "RESOLUTION: $(xrandr | awk '/\*/{printf $1" "}')" printf " %s\n" "MEMORY: $(free -m -h | awk '/Mem/{print $3"/"$2}')" printf "\n" } #------------------------------------------------------------- # Misc functions. #------------------------------------------------------------- function add-line-numbers { awk '{print NR " " $0}' ; } # 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 } # Chops the 1st column. # Example: ls -al | chop-first-column function chop-first-column { awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}' ; } # 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 } # Try to do something and give it 3 attempts for it to work. # (ideal for backup scripts etc when you don’t want to be woken up or turn up to work the following morning to a failed job). try3() { $@ || $@ || $@ } #------------------------------------------------------------- # Mouse functions. #------------------------------------------------------------- # Get mouse cursor coordinates with xdotool function getmousecoords() { xdotool getmouselocation|awk \ '{sub(/^x:/,"",$1);\ sub(/^y:/,"",$2);\ print $1 " " $2}' } #------------------------------------------------------------- # 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 } #------------------------------------------------------------- # Password functions. #------------------------------------------------------------- # Random password generator (8 caractères par défaut) genpasswd() { date +%s | sha256sum | base64 | head -c$1 ;echo } randompw() { cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w ${1:-32} | head -n 1 } # Random number generator. rand() { if [ -z "$1" ] # no argument then range=4 else range=$1 # will error if argument is not a number fi local num for ((i=0;i<$range;i++)) do num=$num$((RANDOM%9)) done echo $num # printf "%s" $num # echo } #------------------------------------------------------------- # 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 } # Kill Processes. # Example: pskill "firefox" pskill () { ps aux | grep $1 > /dev/null mypid=$(pidof $1) if [ "$mypid" != "" ]; then kill -9 $(pidof $1) if [[ "$?" == "0" ]]; then echo "PID $mypid ($1) killed." fi else echo "None killed." fi return; } myuptime () { uptime | awk '{ print "Uptime:", $3, $4, $5 }' | sed 's/,//g' return; } #------------------------------------------------------------- # Programming functions. #------------------------------------------------------------- # A quicker G++. g++11() { echo "g++ -std=c++11 -Wall -Werror ${1}.cpp -o $1"; echo ""; g++ -std=c++11 -Wall -Werror ${1}.cpp -o ${1}.o; } #------------------------------------------------------------- # Sound functions. #------------------------------------------------------------- # Removes audio from a video. # Example: soundremoveaudio input.mp4m output.mp4 soundremoveaudio() { ffmpeg -i $1 -vcodec copy -an $2 } #------------------------------------------------------------- # 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 } 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. strsurround hello \\\" return 1 fi echo $1 | sed "s/^/$2/;s/$/$2/" ; } #------------------------------------------------------------- # Text functions. #------------------------------------------------------------- # Truncate lines longer than 80 characters (for use in pipes). #alias cut80='/usr/bin/cut -c 1-80' #cut80() { echo "$@" | cut -c 1-80 ; } # Surround lines with quotes (useful in pipes). quote() { echo "$@" | /bin/sed 's/^/"/;s/$/"/' ; } # Translate spaces in filenames into underscores. spaces2underscores () { targetdir="$*" if [ ! -z "$1" ] then if [ -d "${targetdir}" ] then oldpwd=$(pwd) else echo "Not a valid directory." return 1 fi fi read -n1 -p "Rename all files in ${targetdir}? [y/N]" case ${REPLY} in "Y" | "y" ) cd "${targetdir}" fncounter=0 for fn in * do newfn=$(printf "${fn}" | tr ' ' '_') if [ "${newfn}" != "${fn}" ] then mv "${fn}" "${newfn}" fncounter=$((${fncounter}+1)) fi done cd "${oldpwd}" echo "Successfully replaced spaces by underscores in ${fncounter} filename(s)." echo ;; * ) echo "Operation aborted." echo return 0 ;; esac unset targetdir oldpwd REPLY fncounter fn newfn } # Translate underscores in filenames into spaces.. underscores2spaces () { targetdir="$*" if [ ! -z "$1" ] then if [ -d "${targetdir}" ] then oldpwd=$(pwd) else echo "Not a valid directory." return 1 fi fi read -n1 -p "Rename all files in ${targetdir}? [y/N]" case ${REPLY} in "Y" | "y" ) cd "${targetdir}" fncounter=0 for fn in * do newfn=$(printf "${fn}" | tr '_' ' ') if [ "${newfn}" != "${fn}" ] then mv "${fn}" "${newfn}" fncounter=$((${fncounter}+1)) fi done cd "${oldpwd}" echo "Successfully replaced underscores by spaces in ${fncounter} filename(s)." echo ;; * ) echo "Operation aborted." echo return 0 ;; esac unset targetdir oldpwd REPLY fncounter fn newfn } #------------------------------------------------------------- # 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$ # 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; } #------------------------------------------------------------- # URL Encode functions. #------------------------------------------------------------- # Transform the arguments into a valid url querystring urlencode() { local args="$@" jq -nr --arg v "$args" '$v|@uri'; }
bash/functions/my_functions.txt · Last modified: 2022/09/18 12:42 by peter