'Exporting variable with a specific log
Problematic
Exporting a variable can be done in KSH via the command:
export EXAMPLE1="A"
export EXAMPLE2="B"
export EXAMPLE3="C"
However I want to echo the user that the variable has been redefined:
echo ${!EXAMPLE1@}" -> "$EXAMPLE1
echo ${!EXAMPLE2@}" -> "$EXAMPLE2
echo ${!EXAMPLE3@}" -> "$EXAMPLE3
The aim is to do both actions in a single line of code because I have several environment variables to assign.
What I've done
To answer the problem, I have made a define function that combines both commands:
define() {
var=$1
val=$2
export var=$val
echo ${!var@}" -> "$var
}
EXAMPLE1="A"
EXAMPLE2="B"
EXAMPLE3="C"
define $EXAMPLE1 "X"
define $EXAMPLE2 "Y"
define $EXAMPLE3 "Z"
But it doesn't give the expected result. Instead of receiving:
EXAMPLE1 -> X
EXAMPLE2 -> Y
EXAMPLE3 -> Z
, I receive the following output:
var -> X
var -> Y
var -> Z
, and the environment variables are still set to A, B and C. It seems that my method assigns the local variable var instead of my environment variable.
What could be a solution to my problem?
Solution 1:[1]
Don't call your function with $EXAMPLE1 but with EXAMPLE1.
I made more modifications:
define() {
var=$1
val=$2
export $var=$val
echo "${var} -> ${val}"
}
EXAMPLE1="A"
EXAMPLE2="B"
EXAMPLE3="C"
define EXAMPLE1 "X"
define EXAMPLE2 "Y"
define EXAMPLE3 "Z"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Walter A |
