I set an array with static values in the code of my script. It basically handles strings and I want to remove some of theses values.
Somehow I didn't find any way to overwrite values of the array in the code of my script.
I can remove values but just in the lifetime of my script. When the script ends, my array is reset to the hardcoded values.
How can I do this?
CodePudding user response:
You can persist, save a modified array state for next runs of your script this way:
#!/usr/bin/env bash
default_fruits=( 'apricot' 'banana' 'cocoa' )
# Try to restore saved fruits array from saved_fruits.sh
if ! . saved_fruits.sh
# if not available, use the default fruits
then fruits=( "${default_fruits[@]}" )
fi
# Print fruits array that will be different after first run
printf 'Fruits:\n'
printf '%s\n' "${fruits[@]}"
# Change the fruits array at run-time
fruits[1]='blueberry'
# Save the array to recover it next time
declare -p fruits >saved_fruits.sh
First time running this script:
apricot
banana
cocoa
Subsequent runs will output:
apricot
blueberry
cocoa