0

It seems like sed is not replacing the string on my code. What I intend for it to do is to change the property called "notification.enable" from false to true from server2 to activate, and, true to false in server1 to deactivate. It works when I do it individually using below but when doesn't when being called from a function.

sed -i 's/notification.enable=false/notification.enable=true/g' /usr/config/activate.properties

function prompt_activate_server2_config {
activate="notification.enable=true"
deactivate="notification.enable=false"
dir=/usr/config
filename=$dir/activate.properties
output=$(grep "notification" $filename)
if [ -e $filename ];
            then
sed -i 's/$deactivate/$activate/g' "$filename"
echo "Activated in Server 2"
echo $output;date
fi
        }

function prompt_deactivate_server1_config {
    activate="notification.enable=true"
    deactivate="notification.enable=false"
    dir=/usr/config
    filename=$dir/activate.properties
    output=$(grep "notification" $filename)
    if [ -e $filename ];
                then
    sed -i 's/$activate/$deactivate/g' "$filename"
    echo "Deactivated in Server 1"
    echo $output;date
    fi
            }

I'm using function because I need to remotely execute the scripts from another server

So I call them using below. All the 'execute' stuff is on the above function. What am I missing?

 if [ "$selection" == 'Activate Config' ]; then

#Activate server1/deactivate server2#
ssh user@server2 "$(typeset -f prompt_activate_server2_config); prompt_activate_server2_config"
sleep 2
ssh user@server1 "$(typeset -f prompt_deactivate_server1_config); prompt_deactivate_server1_config"    
  fi
Ash
  • 19
  • 6

1 Answers1

0

You need to evaluate the two variables ($deactivate and $activate) and you do that by using double rather than single quotes:

sed -i "s/$deactivate/$activate/g" "$filename"

I would write it like this (and use sed rather than grep if you really need to print before/after):

  update_config() {    
          local file=$1
          local key=$2 
          local from=$3
          local to=$4                                                 
          [ -e "$file" ] && sed -i "s/\($key=\)$from/\\1$to/g" "$file"         
  }
   
  update_config /usr/config/activate.properties 'notification\.enable' 'false' 'true'
Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • Edit: I thought it worked, but apparently it didn't. It's still not replacing the string. – Ash Feb 11 '21 at 05:24