6

I have a environment config file where i have defined the environment variables. I use source to get these variables inside my shell script(bash).

I use a checkout command in my shell script which checks out the files from location defined in an environment variable. Now i need to use multiple locations to checkout the files which can be any number for different run of shell script.

For eg. User gives two paths, PATH1 and PATH2 in config file and a NUM_OF_PATHS as 2.

In my shell script I want to do something like below for using path.

i=0
echo ${NUM_OF_PATHS}
while [ $i -lt ${NUM_OF_PATHS} ]
do
    checkout $PATH{$i}
    i=`expr $i + 1`
done

How can I use the variable i to form an environment variable PATH1 or PATH2 etc.?

0

4 Answers 4

7
i=1
while [ $i -le ${NUM_OF_PATHS} ]
do
  CPATH=$(eval echo \$\{PATH$i\})
  echo "PATH$i: $CPATH"
  let i++ 
done

eval combines and evaluates its parameters and executes the combined expression. Here, eval executes: echo ${PATH1}. In order to do this, we first escape the ${...} so that echo can receive them after eval. The only un-escaped special character is $ before i. eval expands this and strips off the escaped characters and executes echo with the result.

So, CPATH=$(eval echo \$\{PATH$i\}) becomes CPATH=$(echo ${PATH1}) and CPATH gets the echo output.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a complete example that I think will do what you want. Below is my original message that was voted down for a reason I don't completely understand:

$ cat test.sh
function checkout() {
    echo "Registering $1"
}

PATH1="Path1;/usr/bin"
PATH2="Path2;/bin"
NUM_OF_PATHS=2

i=1
echo $NUM_OF_PATHS
while [ $i -le $NUM_OF_PATHS ]
do
    eval "checkout \$PATH$i"
    i=`expr $i + 1`
done
$ bash test.sh
2
Registering Path1;/usr/bin
Registering Path2;/bin
$

Original Message You can use the "eval" command. Here is an example (works on GNU bash, version 4.2.37(2)-release):

$ A1="Variable 1"
$ A2="Variable 2"
$ for i in {1..2}; do eval "echo \$A$i"; done
Variable 1
Variable 2
$

The string will evaluate to "echo $A1" and "echo $A2", and then eval will do what you want.

Comments

0

Why don't you use array variable? Use one array MYPATH[] instead multi PATH1 PATH2 variables

MYPATH=(
path0
path1
path2
)
MYPATH[3]=path3

NUM_OF_PATHS="${#MYPATH[@]}"
echo ${NUM_OF_PATHS}

for ((i=0; i < NUM_OF_PATHS; i++))
do
    checkout ${MYPATH[$i]}
done

Comments

-2

Use curly braces around the name: ${PATH$i}

1 Comment

It is not working. I tried all combinations with curly braces. It gives bad substitution error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.