0

How do I expand a brace expansion that originally come from a string variables ? Note that the string variable is a requirement.

#!/usr/bin/env bash

TEXT_DIRS='opt/*/{doc,gtk-doc}'

My intention is reading a bash source from zsh, or maybe other language as well such as Perl or Python. Get the configuration from /etc/makepkg.conf, as below.

DOC_DIRS=(usr/{,local/}{,share/}{doc,gtk-doc} opt/*/{doc,gtk-doc})

It is all, for just, learning purpose. Is that possible, to expand from string ?

1 Answers1

2

The tricky thing here is that once Bash resolves the environment variable, it doesn't make another pass to process its contents again. You'd have to evaluate the content of the variable in another pass of the shell ( eg another shell command).

Here's one way to do that:

bash-4.4# TEXT_DIRS='/usr/*/{bin,src,lib}'
bash-4.4# bash -c ls\ $TEXT_DIRS
ls: /usr/*/src: No such file or directory
/usr/local/bin:

/usr/local/lib:

Here, I'm dynamically generating a shell command that I then evaluate to handle the 2nd expansion. (I took the liberty of changing the paths to something that would match on typical systems, so make sure to change it back if you try to test).

Dynamically generating code is always dangerous, if you can't trust the input. That's essentially how command injection attacks work. But use of eval in your own shell with trusted input is more or less "safe", though I rarely find myself using it unless in a contrived scenario like yours, or some of my own worse ideas.

erik258
  • 14,701
  • 2
  • 25
  • 31
  • Excellent Answer sir. Exactly what I need. Now I can parse bash line in zsh. This is my first post in stackoverflow, forgive my akwardness in commenting. – epsi nurwijayadi Dec 30 '17 at 08:30
  • You did a good job explaining what you were thinking and trying to do, so it was a great first question. Many questions are duplicates at this point, so don't be too disappointed your question was closed. – erik258 Dec 30 '17 at 18:02