bash

→ Some cool stuff one can do in bash, useful for scripts and stuff:

Variable Substitution

→ Search/Replace within ${var}

# Example: Hello to Hallo
foo="Hello"
echo "${foo/e/a}"
# Output:
# Hallo
# Example: escape spaces in strings
var="Hello World, this is Bash"
echo ${var// /\\ }

# Output:
# "Hello\ World,\ this\ is\ Bash"
# Example: Rename File Extension
var="file.txt"
echo ${var//txt/tmp}

# Output:
# file.tmp

extract file name/extension

fullfile="/example/path/to/file.ext"
filename=$(basename -- "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"
echo "Filename: ${filename}, Extension: ${extension}"

# Output:
# $ Filename: file, Extension: ext

reloading the shell

# Reload Shell
exec $SHELL -l

arrays

#!/bin/bash
# declare an array called array and define 3 vales
array=( one two three )
for i in "${array[@]}"
do
    echo $i
done
#!/bin/bash
# Declare a 2-Dimensional Array
declare -A array
array=( ["Key1"]="Value1" ["Key2"]="Value2" )

for i in "${!array[@]}"
do
    echo $i
done
array=( one two three )
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
limits=( 10, 20, 26, 39, 48)
# --------------------------
printf "%s\n" "${array[@]}"
printf "%s\n" "${files[@]}"
printf "%s\n" "${limits[@]}"
# dir_enc=(/share/loc-raw/${encrypted[$folder]}/*/)
for i in "${folders[@]}"
do
    echo $i
done

Stacktrace

  #!/usr/bin/env bash
  #--------------------------------------------
  # Default Bash Script Header
  set -eu
  trap stacktrace EXIT
  function stacktrace {
          if [ $? != 0 ]; then
                  echo -e "\nThe command '$BASH_COMMAND' triggerd a stacktrace:"
                  for i in $(seq 1 $((${#FUNCNAME[@]} - 2))); do j=$(($i+1)); echo -e "\t${BASH_SOURCE[$i]}: ${FUNCNAME[$i]}() called in ${BASH_SOURCE[$j]}:${BASH_LINENO[$i]}"; done
          fi
  }

  SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
  #--------------------------------------------

Move each line in a file to a new sequenced file (001,002,003)

# Our Demo Input:
cat > all.txt << EOF
Hello
World
EOF

a=1
while read -r line
do
    echo "${line}" > $(printf "sentence%03d.txt" "$a")
    let a=a+1
done < all.txt

# Result:
# ./sentence001.xml --> "Hello"
# ./sentence002.xml --> "World"
Trick Command
Variable Substitution (Search/Replace within ${var}) ${var/search/replace}
Access last Command Argument mkdir -p /path/to/dest && mv Foo* $_