0

Is there a way in a shell script to copy text into a local .env file so that I can automate setting those environment variables?

example, I want to copy this to an .env file that sits in the same directory I'm already cd'd to

PIN=1
DEVICE_PREFIX=xxx
DEV=true
PositiveGuy
  • 46,620
  • 110
  • 305
  • 471

3 Answers3

1

Well there are multiple approaches, one that I don't see here is the most simplest

echo "
PIN=1
DEVICE_PREFIX=xxx
DEV=true
" > .env

with echo can do multi line printing and then redirect the output to the file i.e .env

Hope it helps

0
#!/bin/bash

text=$(cat << EOF
PIN=1
DEVICE_PREFIX=xxx
DEV=true
EOF
)

# Specify the path to the .env file
env_file=".env"

# Copy the text to the .env file
echo "$text" > "$env_file"
Manny
  • 30
  • 6
  • 2
    @PositiveGuy you can simply do it on the command line as `cat > your.env << EOF ... EOF` To APPEND and not REPLACE use `cat >> your.env << EOF ... EOF` – David C. Rankin May 17 '23 at 04:02
0

An alternative without creating/saving the data/input to a variable, something like:

#!/usr/bin/env sh

env_file=".env"

cat >> "$env_file" <<'EOF'
PIN=1
DEVICE_PREFIX=xxx
DEV=true
EOF

A note on the redirections ( > and >> ) from the shell.

  • The >> appends to the existing non-empty file.

  • The > Replaces the data/contents of an existing non-empty file.

  • A word of caution, the > truncates an existing file, but both >> and > creates it if it does not exists.

  • See Redirections

Jetchisel
  • 7,493
  • 2
  • 19
  • 18