skip to Main Content

I am trying to update the following line, which appears in a PHP config file, from a shell script that updates the application that is associated with the config file:

$config['version'] = "v2.7.0";

When I run my shell script I pass in the version number to be updated. The shell script includes the following command to search for and replace the line:

sudo sed -i -e '$a$config['version'] = "v$1";' /var/www/app/application/config/production/config.php

Running that results in the following:

$config[version] = "v$1";

I’ve tried all sorts of combinations of escaping quotes but nothing seems to work. Does anyone know what combination will work that keeps the quotes and expands the variable that is passed in? Alternate approaches that will work in a shell script are welcome!

2

Answers


  1. vers="2.7.0"
    sed -i "$a$config['version'] = "v$vers";" configfile
    

    Use double quotes as opposed to single ones and escape the double quotes as well as $

    Login or Signup to reply.
  2. Assuming the value to change is in the form

    $config[version] = "v1.0.0";
    

    and you want to get

    $config[version] = "v2.7.0"; # where v1="v2.7.0"
    

    you can use a sed command (w/o escaping) similar to this:

    sed -i -e '$a$config['version'] = "'"$v1"'";' /path/to/file
    sed -i -e '$a$config['version'] = "'$v1'";' /path/to/file
    

    The former will not break when the v1 contains spaces.

    Explanation:

        sed -i -e '$a$config['version'] = "'"$v1"'";'
                                          ^^^   ^^^ |-- terminates sed command
       places a literal double quote -----|||___|||-- places a literal dbl quote
                                           |  |  |-- returns sed command
               leaves sed's single         |  |  
                 quotation command---------|  |---- variable enclosed
                                                    in double quotes
                                            
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search