Durée max: 10-15 min
## String manipulation Consider `string=abcABC123ABCabc` * string length : `${#string}` is `15` * substring extraction : * `${string:7}` is `23ABCabc` * `${string:7:3}` is `23A` * `${string:(-4)}` or `${string: -4}` is `Cabc` ---
JDF: a mon avis pas utile - `let` make a variable equal to an expression ```bash #!/bin/bash let a=5+4 echo $a # 9 let a++ let "a = 4 * $a" ``` - `expr` : print out the result of the expression ```bash #!/bin/bash expr 5 + 4 # 9 expr 5+4 # boom expr "5 + 4" # boom a=$( expr 10 - 3 ) ``` - double parentheses : return the result of the expression > it is the **preferred method** ---
--- ### Associative arrays = Dictionaries (Bash 4.0 or higher) By default, a bash array is an indexed array : need to use the `declare` command ```bash declare -A acronyms # -A for associative array acronyms[ACK]=Acknowledgement acronyms[EOF]="End of Frame" echo ${acronyms[ACK]} if [ ${acronyms[EOF]+_} ]; then echo "Found"; else echo "Not found"; fi ``` > the variable expansion `${MYVAR+ABC}` expands to `ABC` is `MYVAR` is set and to nothing otherwise ```bash declare -A countries=( [ALB]=Albania [BHR]=Bahrain [CMR]=Cameroon [DNK]=Denmark [EGY]=Egypt ) echo ${countries[@]} echo ${!countries[@]} countries+=( [FJI]=Fiji ) echo ${countries[@]} unset countries[BHR] echo ${countries[@]} ``` <!-- ### About `declare` ```bash declare --help ``` Examples : - declare a variable without a value - force a variable to be an integer only - declare a variable as a **parameter** (read-only) - force a character(s) variable to store all uppercase or lowercase letters - display the attributes and values of all variables - etc.
 --- ```bash #!/bin/bash # How to iterate over keys or values of an Array declare -A fruits fruits[south]="Banana" fruits[north]="Orange" fruits[west]="Passion Fruit" fruits[east]="Pineapple" for key in "${!fruits[@]}" do echo "Key is '$key' => Value is '${fruits[$key]}'" done ```