简体   繁体   中英

How to export bash variable with value as string with hyphen?

I'm running in a simple problem, cannot export a string value with hyphens in bash variables. Here is what's happening:

.env

NAME_0=`Bruno - Souto`
NAME_1="Bruno - Souto"
NAME_2='Bruno - Souto'

export.sh

#!/bin/bash
set -xv

export $(cat .env | egrep -v "(^#.*|^$)" | xargs)

echo ${NAME_0} 
echo ${NAME_1} 
echo ${NAME_2} 

output:

dev@dev:~/teste$ ./export.sh 

export $(cat .env | egrep -v "(^#.*|^$)" | xargs)
++ cat .env
++ xargs
++ egrep -v '(^#.*|^$)'
+ export 'NAME_0=`Bruno' - 'Souto`' NAME_1=Bruno - Souto NAME_2=Bruno - Souto
+ NAME_0='`Bruno'
./export.sh: line 4: export: `-': not a valid identifier
./export.sh: line 4: export: `Souto`': not a valid identifier
+ NAME_1=Bruno
./export.sh: line 4: export: `-': not a valid identifier
+ NAME_2=Bruno
./export.sh: line 4: export: `-': not a valid identifier

echo ${NAME_0} 
+ echo '`Bruno'
`Bruno
echo ${NAME_1} 
+ echo Bruno
Bruno
echo ${NAME_2} 
+ echo Bruno
Bruno

I DO NEED to export with 'xxx - xxx', doesn't matter how. Any ideas?

thks

First assignment ( NAME_0 ) is invalid since the backticks imply that you want to run a command Bruno with arguments - and Souto .

Not sure why you don't just source the file and then manually export the variables (you already know the names - per the echo calls - so go ahead and export , too), eg:

$ source .env
-bash: Bruno: command not found       # result of using backticks in the NAME_0 assigment

$ typeset -p NAME_0 NAME_1 NAME_2
declare -- NAME_0=""
declare -- NAME_1="Bruno - Souto"
declare -- NAME_2="Bruno - Souto"

$ export NAME_0 NAME_1 NAME_2

$ typeset -p NAME_0 NAME_1 NAME_2
declare -x NAME_0=""
declare -x NAME_1="Bruno - Souto"
declare -x NAME_2="Bruno - Souto"

NOTE: NAME_0 is empty due to the use of backticks in .env

With a single liner.. I would skip the quotes in your .env file and read into your bash script with export ..

.env

NAME_0=Bruno - Souto
NAME_1=Bruno - Foo
NAME_2=Bruno - Bar

test.sh

#!/bin/bash

while read -r line; do LANG=C export "$line"; done <".env$1"
echo $NAME_0
echo $NAME_1
echo $NAME_2

output

$ bash test.sh
Bruno - Souto
Bruno - Foo
Bruno - Bar

CLI

~$ while read -r line; do LANG=C export "$line"; done <".env$1"
~$ echo $NAME_0
Bruno - Souto
~$ echo $NAME_1
Bruno - Foo
~$ echo $NAME_2
Bruno - Bar

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