[bash] dynamic variables - assign value containing spaces
I have a lot of repetitive code here and I tried to replace this piece of code with dynamic variables using eval:
Code:
[[ ! -z "$bg" ]] && bg_canvas=$(canvas $bg_colour) Code:
for t in fg bg; do
Any help would be very much appreciated. |
Generally there are very few reasons to use dynamic variable names. My suggestion would be to use associative arrays using the appropriate names, bg & fg, and test and set as needed.
This will also negate the issue you are having with spaces as you simply quote the whole variable. And of course the use of eval should always be kept to a minimum or avoided where possible. |
Thank you for your response, grail.
On this occasion I would find it more convenient to use dynamic variables as I have already used this technique elsewhere in the script. My main stumbling block is 2) - assigning values with spaces to dynamic variables. Is there any way round the problem? For 1) I have a work-around. |
Quote:
That being said, the only way I know of nullifying the space issue is either: 1. use double quotes where necessary 2. assuming the above does not work, replace all spaces with something like an underscore and then reverse the process when needing the space version Generally the idea for me would be, if you need to use option 2 then the overhead associated would mean you need to rethink the design choice. If David H sees this thread he may have other ideas. |
First of all, don't use eval.
Also, and I can't stress this enough, you shouldn't use eval. Last, but not least, DON'T USE EVAL! This is exactly what the associative arrays are for: Code:
#!/bin/bash Code:
#!/bin/bash Code:
#!/bin/bash |
Quote:
Code:
for T in fg bg; do |
Quote:
But neither of you mentioned what's so evil about eval. Quote:
Code:
${!var}=blue |
rknichols, our posts crossed. I am in the process of testing your suggestion.
|
Quote:
|
Just an aside note: instead of
Code:
! -z Code:
-n |
Quote:
|
colucix - thanks for the useful links
|
All times are GMT -5. The time now is 08:00 AM. |