Bash cheat sheet
Cheat sheet verified with Bash 4.4.19
Variables
Set and get
local var="Jan"
echo $var
Arrays
Indexed - Standard arrays with number as index array_var=(value1 value2 value3)
Associative - Index could be any string array_var=([text-index]=value [text-index2]=value2)
Declare
Indexed
array_var=()
array_var=(value1 value2 value3)
declare -a array_var
Associative
declare -A array_var
Conversion from String
Convert string to array. With space separator " “
var_string='string is automatically converted'
array=( "$var_string" )
echo ${array[0]}
Print/Get array elements
Get first array element
array=(value1 value2 value3)
echo ${array[1]}
`value1`
Get all array elements
array=(value1 value2 value3)
echo ${array[@]}
Get array size
echo "${#array[@]}"
Get index of array element
array=(feb may jan)
value='jan'
for i in "${!array[@]}"; do
if [[ "${array[$i]}" = "${value}" ]]; then
echo "${i}";
fi
done
Output:
2
Merge arrays
combined=( "${array1[@]}" "${array2[@]}" )
Merge arrays and remove duplicates
no_duplicates=( $(printf '%s\n' "${array[@]}" | sort -uz) )
Check if array contains some value
function contains(){
if [[ " ${some_array[@]} " =~ " ${some_value} " ]]; then
echo "FOUND"
else
echo "NOT FOUND"
fi
}
Conditionals
Simple if else
if [ "true" = "false" ] then
echo You may go to the party.
elif [ "false" == "true" ] then
echo You may go to the party but be back before midnight.
else
echo You may not go to the party.
fi
test command => In conditionals: []
value=0
[[ $(test $value) -eq 1 ]] || echo "Condition not fulfilled."
Output:
Condition not fulfilled.
String operations
Replace space with new line
echo "String with spaces" | tr ' ' '\n'
Output:
String
with
spaces
Substitute words in variable:
name="Marko"
grade=5
input="Hello I'm #name. My grade is #grade."
command=$(echo "$input" | sed "s/#name/$name/gi" | sed "s/#grade/$grade/gi")
echo $command
Output:
Hello I'm Marko. My grade is 5.
Files
for through files in path
for path in /some/path/*; do
readFile "${path}"
done
Read line in a file with empty lines, spaces and comments removal
sed -e 's/[[:space:]]*#.*// ; /^[[:space:]]*$/d' $1 | while IFS= read -r line || [ -n "$line" ];
do
echo $line
done
Tags: Bash
Maybe you want to share? :)