-1

I am writing a bash script to automate the task of setting environment variables for my project. but when I execute my bash script using sh env.sh (env.sh is my file name). I am able to get value from the AWS secret manager and when I do echo inside the bash script I am able to print the env variable but when I run the echo $variable after the bash file is executed then it returns nothing.

I tried replacing eval to source but no luck

also i searched on stackoverflow for the issue but none of them helped.

find the script below

  #! /usr/bin/env bash

if [[ "$OSTYPE" == "darwin"* ]]; then
 echo 'running'
 if ! [ -x "$(command -v aws)" ]; then
  echo 'Aws is not installed. Installing aws............................' >&2
  curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
  if ! [ $(id -u) = 0 ]; then
   echo "The script need to be run as root." >&2
   exit 1
  fi
  sudo installer -pkg AWSCLIV2.pkg -target /
  if ! [ -x "$(command -v aws)" ]; then
   echo 'There was some issue installing aws cli. Install aws-cli manually and then run the script!!!' >&2
   exit 1
   fi
   echo "Running aws command please enter the aws access key and secrect"
   aws configure
  fi
   aws secretsmanager get-secret-value --secret-id abc --query SecretString --output text | jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' > /tmp/secrets.env
   eval $(cat /tmp/secrets.env | sed 's/^/export /')
fi

I am currently running this bash file on Mac OS, but I would like it to operate on any OS.

Prashant
  • 90
  • 1
  • 12

1 Answers1

0

If the file contained enviroment variable names setup_local_env.sh, Try

source setup_local_env.sh

This will add them to your current session.

There is another solution called dot source. Check the reference here

. ./setup_local_env.sh

The reason if you directly run ./setup_local_env.sh, it does not work, is because it creates a new bash process, and sets the environment variable there, and then it's lost once the new bash process exits.

Xin Cheng
  • 1,432
  • 10
  • 17
Zasz
  • 12,330
  • 9
  • 43
  • 63