0

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

1 Answer 1

0

You should replace

grep ^recentdirs > defaults.cfg

with

sexp="s[^recentdirs.*[recentdirs=(${newdir[@]} ${recentdirs[@]})["
sed -i -e "$sexp" defaults.cfg
2
  • Thank you for that fast solution. May I ask you why you chose [ as the sed delimiter? I though one should choose a delimiter that is not within the pattern? Commented Apr 26, 2018 at 13:39
  • Yes, I used '[' instead of the usual '/' delimiter in sed command since the latter would conflict with '/' in directories path. Commented Apr 26, 2018 at 15:24

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.