My linux world » bash

bash


Contents

Hash tables

# First, declare associative array:
declare -A myAssociativeArray
 
# Then, fill your array:
myAssociativeArray=( ["key1"]="value1" ["key2"]="value2")
 
# Finally, display:
echo "${myAssociativeArray["key1"]}"
 
# You can iterate elements like this:
for element in "${!myAssociativeArray[@])}";
do
  echo "$element <=> ${myAssociativeArray["$element"]}";
done

Split String

# split string MYSTRING with delimiter “;”
MYSTRING="string1;string2"
 
OIFS="$IFS"
IFS=";"
 
read -a array <<< "${MYSTRING}"
 
echo $array
 
count=${#array[@]}
echo "count: $count"
 
echo "element 1: ${array[0]}"
echo "element 2: ${array[1]}"

String contains

string='My string';
 
if [[ $string == *My* ]]
then
  echo "It contains!";
fi

Replace string by another

MYNEWSTRING=$(echo $MYSTRING| sed 's/OLDSTRING/NEWSTRING/g')

Copy one array to an other

# array
array1=("elt1","elt2","elt3")
 
# copy array1 content to array2
array2=("${array1[@]}")
 
# print array2 values:
for val in "${array2 [@]}" ; do
   echo "$val" 
done

Quick create file using heredoc

mystring="hello world"
 
cat > /tmp/heredoc.txt << EOF
echo "this should NOT expand 'mystring' var"
echo \$mystring
echo
echo "this should expand 'mystring' var"
echo $mystring
EOF

and the result :

[root@localhost ~]# cat /tmp/heredoc.txt
echo "this should NOT expand 'mystring' var"
echo $mystring
echo
echo "this should expand 'mystring' var"
echo hello world

Loop though only directories

for d in */ ; do
    echo "$d"
done

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub