In a bash script, I wish to pass in a string which is contained in a variable, and contains up to 3 substrings separated by the '+' symbol. Each substring will have a specific numeric value, sort of like an octal mode.
I'd like to split the string into the substrings, convert them to their numeric value, and add the values together.
For instance if my substrings and values are:
- hat = 1
- shirt = 2
- trousers = 4
And my variable containing these in a string is:
my_outfit=shirt+trousers
I'd like a variable called outfit_value
to have a value of 6. How should I go about doing this?
I've thought about setting IFS
to '+' and reading the variable into an array, then looping through the array and converting each element to its value. Unfortunately, my head turns to custard when I think about retrieving these numeric value elements and doing an arithmetic expression.
EDIT:
This is what I have so far, it seems to work, but I'd like to know if there are any problems, or if it could be done more safely/efficiently:
my_outfit=hat+shirt+trousers
oIFS=$IFS
IFS=+
read -a clothes <<< "$my_outfit"
IFS=$oIFS
outfit_value=0
for string in ${clothes[@]}
do
if [[ $string = "hat" ]]
then
add_value=1
elif [[ $string = "shirt" ]]
then
add_value=2
elif [[ $string = "trousers" ]]
then
add_value=4
fi
let outfit_value="$outfit_value"+"$add_value"
done
echo "OUTFIT VALUE is $outfit_value"