1

I would like to source some dotfiles. I've found interesting solutions using brace expand. I know this is maybe bash anti pattern, but wondering if it's somehow possible to brace expand from variable. Like this:

dotfiles={path,env,alias}
for dotfile in "$HOME/.dotfiles"/.$dotfiles;
do
    echo $dotfile
done

The above example of course doesn't print path env alias. Consider this as hypothetical question about possibilities of brace expansion, not a solution to some problem.

mauron85
  • 1,364
  • 1
  • 14
  • 28
  • See [BashPitfalls #33](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.7B1...24n.7D): Brace expansion happens *before* parameter expansion, so you can't use results of a parameter expansion to do brace expansion. – Charles Duffy Mar 04 '19 at 21:17
  • Circumventing that typically means using `eval`, and that [*is* an antipattern](https://mywiki.wooledge.org/BashFAQ/048). – Charles Duffy Mar 04 '19 at 21:18
  • ...what you *can* do while staying clear of practices generally-considered-evil is use brace expansion to load an array: `dotfiles=( "$HOME/.dotfiles/".{path,env,alias} ); for dotfile in "${dotfiles[@]}"; do ...` – Charles Duffy Mar 04 '19 at 21:21
  • Thanks for the link. Now I'm sure I cannot just use it as an alternative to an array (without using eval). You can post this as an answer. Will accept it. – mauron85 Mar 04 '19 at 21:22
  • Anyway, just wondering how syntax with eval will look like. – mauron85 Mar 04 '19 at 21:22
  • `eval 'dotfiles_arr=( "$HOME/.dotfiles"/.'"$dotfiles"' )'`, then `for dotfile in "${dotfiles_arr[@]}"` is an example of what it would look like with `eval`. Note that that *completely trusts* the value of your `dotfiles` variable -- hostile code in there could run any arbitrary command it wanted to, which is why this practice should never be used when inputs are from a source that could even *potentially* be influenced by a user on the other end of a privilege boundary (filenames are a common example in that category). – Charles Duffy Mar 04 '19 at 21:27
  • excellent. may thanks. – mauron85 Mar 04 '19 at 21:27

0 Answers0