bash
This demonstrates various operations on a Bash associative array (dictionary), including accessing, retrieving, and manipulating key-value pairs.
declare -A sounds sounds["dog"]="woof" echo "${sounds[dog]}" # Dog's sound echo "${sounds[@]}" # All values echo "${!sounds[@]}" # All keys echo "${#sounds[@]}" # Number of elements unset sounds[dog] # Delete dog
bash internaldata manipulationsarray manipulationsassociative array (dictionary)
bash
This demonstrates various array operations in Bash, including pushing, removing, duplicating, concatenating, and reading from a file.
Fruits=("${Fruits[@]}" "Watermelon") # Push Fruits+=('Watermelon') # Also Push Fruits=( "${Fruits[@]/Ap*/}" ) # Remove by regex match unset Fruits[2] # Remove one item Fruits=("${Fruits[@]}") # Duplicate Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate lines=(`cat "logfile"`) # Read from file
bash internaldata manipulationsarray operationspush elements
bash
This code uses a regular expression to extract an email address from a string, demonstrating regex-based pattern matching and extraction in Bash.
string="Hello, my email is user@example.com" # Use regex to match an email address if [[ $string =~ [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} ]]; then echo "Email found: ${BASH_REMATCH[0]}" else echo "No email found." fi
bash internaldata manipulationsstring manipulation and expansionsregular expressions (regex)
bash
This demonstrates the usage of positional arguments in Bash scripts and functions.
$1 # first argument passed to a script or function $# # the number of arguments passed to a script or functio $* # all the arguments passed to a script or function, treating them as a single string $@ # all the arguments passed to a script or function, treating them as an array
bash internaldata manipulationspositional argumentspositional argument