Hey folks! I'm using environment variables to bookmark some folders I frequently access. I've started using fzf for a better UI and would love to pass my list of bookmarks into it. However, when I try to store these bookmarks in an associative array, they're just treated as strings rather than evaluated variables.
For example, I have an environment variable like this:
```export BOOKS="${HOME}/Documents/Books/"```
When I process this in a loop to fill my associative array, I end up with something like `bookmarks["BOOKS"]="${HOME}/Documents/Books/"` instead of having the path expanded to `/home/name/Documents/Books`.
I've tried moving my bookmarks to a separate file and sourcing it based on someone's suggestion but couldn't make that work effectively. I know eval exists, but I've been advised against using it. Does anyone have suggestions for this? Thanks a ton!
2 Answers
I found a straightforward solution that doesn’t rely on external commands. You could use a while loop to read your env file:
```bash
while IFS='=' read -r lhs rhs; do
[[ -z "$lhs" || -z "$rhs" ]] && continue
declare "$lhs"="$rhs"
done < envfile | redirect_pipe_command
```
This would allow the variables to be defined right in your script. If you want to expand variables on the right-hand side, just go with `$(eval echo "${rhs}")`. While using eval has its risks, in this case, it seems to serve the purpose for expanding variables effectively!
If you're aiming for an associative array, just declare it normally using `lhs` as your key and `rhs` as the associated value.
You might want to check out `envsubst`. It’s a handy tool that can help with variable substitution in your strings. Just make sure to pipe your input through it correctly! It’s worth a shot for your requirements!
Will this actually evaluate the variables, though?

So, eval is okay to use in situations like these? I thought the general advice was to avoid it.