When working with Linux, it is common to define environment variables to store configuration values and other important data. However, there may be situations where you need to substitute these environment variables in files or scripts. This is where the envsubst
command comes in handy.
Envsubst
is a command-line tool that replaces variables in a text with their values from the environment. This can be extremely useful when you want to dynamically populate configuration files or scripts with environment variable values.
Here’s a simple guide on how to use envsubst
to replace environment variables in Linux:
- Install
envsubst
if it is not already installed on your system. It is part of the GNU gettext package, so you can install it by running the following command:
sudo apt install gettext
- Create a sample text file with environment variables that you want to substitute. For example, create a file named
example.txt
with the following content:
Hello, my name is $USERNAME and I am using $OS.
- Set the environment variables that you want to substitute. For example, set the
USERNAME
andOS
variables with the following commands:
export USERNAME="John Doe"
export OS="Ubuntu"
- Use the
envsubst
command to replace the environment variables in the text file. Run the following command:
envsubst < example.txt
This command will output the following text:
Hello, my name is John Doe and I am using Ubuntu.
You can redirect this output to a new file if you want to save the substituted text. For example, you can run the following command to save the substituted text to a file named output.txt
:
envsubst < example.txt > output.txt
And that’s it! You have successfully used envsubst
to replace environment variables in Linux. This can be particularly helpful when automating tasks or configuring applications that rely on environment variables for customization.
In conclusion, envsubst
is a powerful tool for dynamically substituting environment variables in text files or scripts. By following the simple steps outlined above, you can easily replace environment variables in Linux and streamline your workflow.