I have written a script that is reading an array: recentdirs with directory names from an external config file called: defaults.cfg and the user can either chose one of the directories from the list or enter a new one. If the user enters a new directory I want this to be stored as the first position in the array recentdirs and saved back in the config file defaults.cfg . The script is able to do this BUT in the current form it is overwriting the file defaults.cfg and thus loosing all other values I'd like to store in it. I have played with ">>" but then the array will be added to the end of the file instead of modified.
directory_select.sh
#!/bin/bash
number=0
source defaults.cfg
for i in "${recentdirs[@]}"
do
#only show the last 5 directories
if [ $number -le 5 ]
then
echo "$number - $i"
number=$((number+1))
else
break
fi
done
read selection
#check if number or string was entered
regpat='^[0-9]+$'
if ! [[ $selection =~ $regpat ]]
then
newdir=( ${selection} )
#merge arrays to have the new entry at the first position
recentdirs=("${newdir[@]}" "${recentdirs[@]}")
#write array back into file
set | grep ^recentdirs > defaults.cfg
else
echo ${recentdirs[$selection]}
fi
Content of defaults.cfg
recentdirs=([0]="/new/folder/" [1]="/folderA/folder1/" [2]="/folderB/folder2/" [3]="/folderX/folder5")
EDIT Working version:
#!/bin/bash
number=0
source defaults.cfg
for i in "${recentdirs[@]}"
do
#only show the last 5 directories
if [ $number -le 5 ]
then
echo "$number - $i"
number=$((number+1))
else
break
fi
done
read selection
#check if number or string was entered
regpat='^[0-9]+$'
if ! [[ $selection =~ $regpat ]]
then
newdir=( ${selection} )
#merge and write array back into file with sed
sexp="s[^recentdirs.*[recentdirs=(${newdir[@]} ${recentdirs[@]})["
sed -i -e "$sexp" defaults.cfg
else
echo ${recentdirs[$selection]}
fi