Skip to main content

My collection of useful bash functions

Published: 2019-05-30 | Lastmod: 2019-06-12

This is a living document. If relevant, I include an example usage after the function definition. Functions are geared towards Mac, but can be easily adapted to Linux.

bash_profile_open #

Open .bash_profile with vscode:

bash_profile_open() {
  code ~/.bash_profile
}

bash_profile_source #

Source .bash_profile changes:

bash_profile_source() {
  source ~/.bash_profile
}

pretty_print_path #

Pretty print PATH:

pretty_print_path() {
  echo $PATH | tr ':' '\n'
}
$ pretty_print_path
/home/zwbetz/bin
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin

log #

Log something and timestamp it:

log() {
  echo -e "[$(date +'%a %F %T %z')] ${@}"
}
$ log Some text here
[Thu 2019-05-30 21:58:08 -0500] Some text here

to_lowercase #

Convert string to lowercase:

to_lowercase() {
  echo "$@" | tr '[:upper:]' '[:lower:]'
}
$ to_lowercase SOME TEXT
some text

to_uppercase #

Convert string to uppercase:

to_uppercase() {
  echo "$@" | tr '[:lower:]' '[:upper:]' 
}
$ to_uppercase some text
SOME TEXT

length #

Get string length:

length() {
  size=${#1} 
  echo "$size"
}
$ length gohugo
6

iso_8601_date #

Get the current date in ISO 8601 format, as UTC.

iso_8601_date() {
  date -u +'%Y-%m-%dT%H:%M:%SZ'
}
$ iso_8601_date
2019-06-12T00:34:41Z

timestamp #

Generate a file-friendly timestamp.

timestamp() {
  date +'%Y-%m-%d_%H-%M-%S'
}
$ timestamp
2019-06-11_19-34-58
$ touch foo_$(timestamp).txt
$ ls
foo_2019-06-11_19-34-58.txt

count_bytes #

count_bytes() {
  wc -c < "$1" | tr -d ' '
}
$ printf "My life has been the poem I would have writ\nBut I could not both live and utter it.\n" > foo.txt
$ count_bytes foo.txt
84

count_chars #

count_chars() {
  wc -m < "$1" | tr -d ' '
}
$ printf "My life has been the poem I would have writ\nBut I could not both live and utter it.\n" > foo.txt
$ count_chars foo.txt
84

count_words #

count_words() {
  wc -w < "$1" | tr -d ' '
}
$ printf "My life has been the poem I would have writ\nBut I could not both live and utter it.\n" > foo.txt
$ count_words foo.txt
19

count_lines #

count_lines() {
  wc -l < "$1" | tr -d ' '
}
$ printf "My life has been the poem I would have writ\nBut I could not both live and utter it.\n" > foo.txt
$ count_lines foo.txt
2