I have an array that contains variable names. In these variables I am assigning values using cycle. Then I am passing these variable names with assigned values ot another function, which checks valid input.
What I need to acomplish is to check if the variable's value contains specific symbol, and if it does, then truncate this value.
Example: when asked for "Admin gateway: " I enter for example value 192.168.1.254/20 (which is nonsense), I want this value to be truncated to 192.168.1.254
Following initialization $1="something" does not work, it returns error admGW=192.168.1.254: command not found
I have tried something like declare $1="something", but this will only create another local variable visible within current function. I need to reinitialize existing global variable instead. This is maybe not the best approach, but I'm curious if this kind of variable initialization is possible.
Sample code:
#!/bin/bash
read_variables(){
all_vars_desc=("Admin IP/mask: " "Admin gateway: ")
all_vars_name=("admIP" "admGW")
for ((i=0; i<${#all_vars_desc[*]}; i++)); do
read -p "${all_vars_desc[$i]}" ${all_vars_name[$i]}
check_value ${all_vars_name[$i]} "${!all_vars_name[$i]}"
done
}
check_value(){
case $1 in
*IP) ;; #some code
*GW) if [[ "$2" == */* ]]; then
$1=$(echo "$2" | awk -F/ '{print $1}')
echo "Truncating to ${!1}"
fi;;
esac
}
read_variables