create a Makefile that replaces strings inside a .sh file from an env file

Makefile tutorial replace strings in shell script from environment file

This refinement specifies the context of using a Makefile and emphasizes the action of replacing strings in a shell script, which will yield more focused and relevant results on tutorials and examples.

To create a Makefile that replaces strings inside a .sh file using values from an .env file, we will leverage shell utilities like sed for substitution, while Makefile rules will help manage this process efficiently. Here’s a step-by-step guide to achieving this.

Understanding the Components

.env File

Typically, an .env file is formatted with key-value pairs that represent environment variables. For instance:

# .env file
DATABASE_URL=mysql://user:password@localhost/dbname
API_KEY=secret_api_key

Target .sh Script

Let’s assume you have a shell script file named script.sh that contains placeholder values for these variables:

#!/bin/bash

echo "Connecting to database at ${DATABASE_URL}"
echo "Using API Key: ${API_KEY}"

Makefile Setup

The Makefile will read the .env file, export those variables, and use them to replace placeholders in script.sh.

Sample Makefile

Below is an example of how to set up your Makefile to replace strings in the .sh file based on the values from the .env file:

# Makefile

# Define the target shell script and the env file
SCRIPT = script.sh
ENV_FILE = .env

# Default target
all: replace

# Target to replace strings in the shell script
replace: $(ENV_FILE)
	@echo "Replacing placeholders in $(SCRIPT) using $(ENV_FILE)..."
	@set -a; . $(ENV_FILE); set +a; \
    sed -e "s|\${DATABASE_URL}|$$DATABASE_URL|g" \
        -e "s|\${API_KEY}|$$API_KEY|g" \
        $(SCRIPT) > tmp_script.sh && \
    mv tmp_script.sh $(SCRIPT) && \
    echo "Replacements done."

# Clean target
clean:
	rm -f $(SCRIPT)

.PHONY: all replace clean

Explanation of the Makefile

  • Variables: SCRIPT and ENV_FILE are defined as the names of your shell script and environment file, respectively.

  • Default Target: The all target, which is invoked when you run make, depends on the replace target.

  • Replace Target: This contains the commands that will:

    • Load environment variables from .env using the set -a and set +a commands, enabling the export of variables for use within the same shell.
    • Use sed with the -e flag to perform regex-based replacements in script.sh. The g at the end of each sed command option indicates a global replacement of the placeholders.
    • Redirect the output to a temporary file (tmp_script.sh), which is then moved back to the original script.sh.
  • Clear Target: This optional clean target can be used to remove the original .sh file, in case you need to reset your script before running replacements again.

Running the Makefile

To execute the replacement process:

  1. Save the .env file and script.sh in the same directory as your Makefile.
  2. Open your terminal, navigate to the directory containing these files, and run:
make

After running this command, your script.sh should now have the actual values from the .env file embedded in it.

Conclusion

This approach allows you to dynamically replace placeholders in your shell scripts with actual values defined in an environmental file. By utilizing Makefiles, you can streamline your build and configuration processes effectively, making your deployments more consistent and manageable.

Feel free to modify the variables and commands in the Makefile according to your specific requirements to enhance its functionality, such as handling additional environment variables or scripts.

People Also Ask

Related Searches

Sources

10
1
Replace a string in shell script using a variable - unix - Stack Overflow
Stack Overflow

I am using the below code for replacing a string inside a shell script. echo $LINE | sed -e 's/12345678/"$replace"/g' but it's getting replaced with $replace ...

2
Makefile Tutorial By Example
Makefiletutorial

This tutorial will focus on the C/C++ compilation use case. Here's an example dependency graph that you might build with Make. If any file's dependencies ...

3
How to write exactly bash scripts into Makefiles?
Unix

You can define your script as a variable using the multi-line definition syntax, and then use the value function to use the raw value of the variable, ...

4
Replacing make with a Shell Script for Running Your Project's Tasks
YouTube

I'm enjoying this shell script set up to replace a Makefile that's being used as a glorified aliases file. Hit the subscribe button to ...

5
Understanding and Using Makefile Variables - Earthly Blog
Earthly

Learn all about Makefile variables and how to use them to automate complex processes in your code. Find out how to set variables, ...

6
Replace environment variables in a file with their actual values?
Unix

envsubst < infile will replace the environment variables in your file with their corresponding value. The variable names must consist solely of alphanumeric or ...

7
GNU Make Manual
Gnu

In this chapter, we will discuss a simple makefile that describes how to compile and link a text editor which consists of eight C source files ...

8
Replace string in a file w/ a variable value - Unix Linux Community
Community

I am trying to replace the default home page for several mac user accounts, I wrote a script that will hunt the files down and replace them ...

9
Is your makefile supposed to be a justfile? : r/golang - Reddit
Reddit

This means what you need (short of a shell script) is a way to run tasks and maybe create dependencies between the tasks, and just is more than ...

10
Make - The Grymoire!
Grymoire

Make is an excellent program that can help you compile programs. But suppose you are just writing shell scripts? Make isn't really needed, right?