Skip to content

Instantly share code, notes, and snippets.

@davidreuss
Created July 10, 2009 11:46
Show Gist options
  • Save davidreuss/144420 to your computer and use it in GitHub Desktop.
Save davidreuss/144420 to your computer and use it in GitHub Desktop.
useful bashisms
#!/bin/bash
# Default variable if not set
[ -z "${var:-}" ] && var="Default..."
echo "$var"
# array declaration
names=(Adam David Johnny Black Abraham)
# array expansion
for item in ${names[@]}; do
echo "$item"
done
# array count
echo ${#names}
# delete pattern in array
echo ${names[@]##A*} # David Johnny Black
# string operations
str="thisisaverylongstring"
# substrings
echo ${str:4} # isaverylongstring
echo ${str:6:5} # avery
echo ${str%string} # thisisaverylong
# replaces first occurence
echo ${str/i/_i_} # th_i_sisaverylongstring
# replaces every occurence
echo ${str//i/_i_} # th__i__s__i__saverylongstr__i__ng
@vackosar
Copy link

vackosar commented May 3, 2015

First one is not Bashism. It is defined by POSIX: http://pubs.opengroup.org/onlinepubs/9699919799//utilities/V3_chap02.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment