How to Assign Variables Based on Another Variable in Bash?

0
10
Asked By CuriousCoder42 On

I'm trying to assign values from one set of variables, where part of each variable is defined by another variable, into a different set of variables that also has dependencies like that. Specifically, I have three characters, 'X', 'Y', and 'Z', and I want to fill up five character variables with those, repeating them as needed.

Here's what I started with:
```
char1=X
char2=Y
char3=Z
char4=
char5=

n=1

result1=0
result2=0
result3=0
result4=0
result5=0

length=3
```

The goal is to achieve this:
```
char1=X
char2=Y
char3=Z
char4=X
char5=Y
```

I've been using a `while` loop to incrementally fill the character variables, but I've been having trouble with the syntax. I tried using `eval`, but I only seem to get the last variable's name instead of its value. What can I do to fix this?

3 Answers

Answered By ScriptingNinja On

Definitely consider looking into 'bash parameter expansion'. It can help you manipulate strings without complex structures. For instance, if you have a string you want to expand or repeat, you can do:
```bash
FOO="0123456"
echo "${FOO:0:5}" # outputs 01234
```

You can repeat your character string and trim it down to what you need. Keep experimenting, and you'll get the hang of it!

Answered By TechScribe89 On

You might want to use indirection. Instead of directly assigning values, you can do something like this:

```bash
varname="char$n"
valor="
${!varname}`
resultname="result$length"
declare "$resultname"="$valor"
```

But also consider learning about arrays in Bash. They could be helpful and simplify your code a lot!

CodeLearner22 -

I get what you're saying about arrays. I haven’t used them before because I wasn’t sure how they worked or if they'd help with my issue. But now I think it's time to learn. Thanks for the suggestion!

Answered By ShellGuru77 On

Try this code snippet instead:
```bash
(n=1; for c in X Y Z; do eval char$n="$c"; n=$((n+1)); done; unset c; while [ "$n" -le 5 ]; do eval char$n=; n=$((n+1)); done; length=3; until [[ $length -eq 5 ]]; do length=$((length + 1)); eval char$length=$char$n; n=$((n + 1)); done; )
```
This should set your characters correctly by re-evaluating your variables at each step. Just keep an eye on how you quote the commands!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.