Shell/Bash¶
Error handling¶
set -o errexit
set -o errtrace
set -o pipefail
set -o nounset
Count chars in string¶
$ foo="Test123"
$ grep -o "s" <<<"$foo" | wc -l
7
IFs¶
Check if the given string exists in given stuff¶
$ foo="Test123"
$ if foo | grep -q "Test"; then echo "Test exists in foo"; fi
Remove leading and trailing spaces¶
FOO=' test test test '
FOO_NO_EXTERNAL_SPACE="$(echo -e "${FOO}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
echo -e "FOO_NO_EXTERNAL_SPACE='${FOO_NO_EXTERNAL_SPACE}'"
# > FOO_NO_EXTERNAL_SPACE='test test test'
echo -e "length(FOO_NO_EXTERNAL_SPACE)==${#FOO_NO_EXTERNAL_SPACE}"
# > length(FOO_NO_EXTERNAL_SPACE)==14
Source: https://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-a-bash-variable
Styling¶
Bold, Italic, Underline, etc.¶
echo -e '\033[1mYOUR_STRING\033[0m'
Explanation:
echo -e- The -e option means that escaped (backslashed) strings will be interpreted\033- escaped sequence represents beginning/ending of the style- lowercase
m- indicates the end of the sequence 1- Bold attribute (see below for more)[0m- resets all attributes, colors, formatting, etc.
The possible integers are:
0- Normal Style1- Bold2- Dim3- Italic4- Underlined5- Blinking7- Reverse8- Invisible
Source: https://stackoverflow.com/a/42449998
History¶
Show history for specific date(s)¶
# Samples:
# history-by-date 2025-02-15
# history-by-date "2025-02-15|2025-02-16"
function history-by-date() {
history 0 | awk '{for(i=2;i<=NF;i++){ printf("%s",( (i>2) ? OFS : "" ) $i) } ; print "";}' | grep --color=never -E "^($1)"
}