简体   繁体   中英

export environment varible from bash script with argument

I am trying to export environment variable using a bash script which takes one argument. I tried to run the script using source command, but it does not work.

source ./script.sh dev

My example script below

#!/bin/bash
# Check 1 argument is passed with the script
if [ $# -ne 1 ]
then
        echo "Usage : $0 AWS account: e.g. $0 dev"
        exit 0
fi

# convert the input to uppercase
aws_env=$( tr '[:lower:]' '[:upper:]' <<<"$1" )


if ! [[ "$aws_env" =~ ^(DEV|UAT|TRN|PROD)$ ]]; then 
    # check that correct account is provided
    echo "Enter correct AWS account: dev or uat or trn or prod"
    exit 0

else
    # export environment variables
    file="/home/xyz/.aws/key_${aws_env}"
    IFS=$'\n' read -d '' -r -a lines < $file
    export AWS_ACCESS_KEY_ID=${lines[0]}
    export AWS_SECRET_ACCESS_KEY=${lines[1]}
    export AWS_DEFAULT_REGION=ap-southeast-2
    echo "AWS access keys and secret has been exported as environment variables for $aws_env account"
fi

Content of file /home/xyz/.aws/key_DEV. Its a sample only, not real keys.

$ cat key_DEV 
123
xyz
    

Try using mapfile instead of read like so...

#!/usr/bin/env bash

# Check 1 argument is passed with the script
if [ $# -ne 1 ]
then
        echo "Usage : $0 AWS account: e.g. $0 dev"
        exit 0
fi

# convert the input to uppercase
aws_env=$( tr '[:lower:]' '[:upper:]' <<<"$1" )


if ! [[ "$aws_env" =~ ^(DEV|UAT|TRN|PROD)$ ]]; then 
    # check that correct account is provided
    echo "Enter correct AWS account: dev or uat or trn or prod"
    exit 0

else
    # export environment variables
    file="/home/xyz/.aws/key_${aws_env}"

    # IFS=$'\n' read -d '' -r -a lines < $file
    mapfile -t lines < "$file"

    export AWS_ACCESS_KEY_ID=${lines[0]}
    export AWS_SECRET_ACCESS_KEY=${lines[1]}
    export AWS_DEFAULT_REGION=ap-southeast-2
    echo "AWS access keys and secret has been exported as environment variables for $aws_env account"
fi

Make sure you also put quotation marks around "$file"

Another little tip, Bash supports making variables uppercase directly, like so:

var="upper"
echo "${var^^}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM