1

I'm learning BASH and trying to create a script that generates a configuration file in which I want to use variables. But of course, like this is a text file, the variable ${MONGO_PORT} is not being replaced by the value i need.

(
cat << MONGOD_CONF
# /etc/mongod.conf

systemLog:
    destination: file
    path: /datos/log/mongod.log
    logAppend: true

storage:
    dbPath: /datos/db
    engine: wiredTiger

net:
    port: ${MONGO_PORT}

security:
    authorization: enabled    
MONGOD_CONF
) > /etc/mongod.conf
  • The first problem is about permission to create the file that I'm avoiding by creating the file in /tmp and moving it to /etc. Because this doesn't work.

        sudo cat << MONGOD_CONF
    
  • The second and more important is about how to replace de variable by the value

Any way to make this work?

Thank you!

2 Answers 2

1

If MONGO_PART is set, the here-document is subject to parameter expansion and you'll get the parameter value in your file.

Use tee instead of cat, which can open the output file itself:

sudo tee /etc/mongod.conf > /dev/null << MONGOD_CONF
    ...
MONGOD_CONF
Sign up to request clarification or add additional context in comments.

Comments

0

When you execute a script with sudo ... the script will be executed with new environment. This is done for safety - to prevent injection of environment variables that may change the script behavior.

Two options to solve the problem: expand the config file as normal user, and perform the saving as sudu, or Use one of the options to allow environment variables to be passed to the sudo call

The first alternative is to change the script to expand the configuration file as the current user (with access to all parameters), and use the sudo only to place the file into /etc

(sudo cat > /etc/mongod.conf) <<MONGOD_CONF
...
MONGOD_CONF

The alternative option is to use --preserve-env option (possible to specify multiple variables as comma separated list).

sudo --preserve-env=MONGO_PORT

Strongly suggested to avoid the -E (--preserve-env, without parameters), as it may open the script to security exploitation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.