I have a config file like this:

# Default LIST="nil"
LIST="element1 element2 element3"

What would be the simplest way to modify LIST from a shell script?

  • 1
    Can you elaborate on what you have in mind? What's the goal and what have you tried so far? – eblock Jan 23 at 10:06
  • I believe the rest of the details would convolute the question. – Alberto Salvia Novella Jan 23 at 10:13
  • 1
    @AlbertoSalviaNovella I believe you should state what you are after. If you have multiple strings in a variable you probably want an array variable like list=( element1 element2 element3 ) – Valentin Bajrami Jan 23 at 10:19
  • The variable I want to modify is already defined as a single string, but thanks for the point. – Alberto Salvia Novella Jan 23 at 10:43

Use sed:

sed -i 's/LIST\=.*/LIST="element4 element5"/' config_file

If you only want LIST to be updated if it's not commented, add ^ (start of line):

sed -i 's/^LIST\=.*/LIST="element4 element5"/' config_file
  • I detected an issue. If LIST is in COMMENT, it will also be changed there. – Alberto Salvia Novella Jan 23 at 11:31
  • Thats not a bug, it's a feature ;-) See my update. – pLumo Jan 23 at 11:34
  • Now it works nicely :P – Alberto Salvia Novella Jan 23 at 12:21

Same answer as the accepted one, but ready to use in a script. In case someone finds it useful:

#! /bin/bash
#  (GPL3+) Alberto Salvia Novella (es20490446e)

modifyVariableInFile () {

    if [ ! -f "${file}" ]; then
        echo "modifyVariableInFile: file doesn't exist: ${file}"
        exit 1

    sed -i "s/^${variable}\=.*/${variable}=\"${content}\"/" "${file}"

modifyVariableInFile ${@}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.