I need to expand some pathes using a POSIX sh or Bash:
Here are two example patterns (I chose overly complicated patterns on purpose):
$ npm pkg get workspaces | jq -r '.[]' apps/app* lib/{be,fe *} lib/*lib Let's say my directory tree looks like this:
$ mkdir -p "lib/be lib/fantastic lib" "lib/fantastic" "lib/fe 1 lib/other lib" "apps/app1" "apps/app2" "be" "1" $ tree . ├── 1 ├── apps │ ├── app1 │ └── app2 ├── be └── lib ├── be lib │ └── fantastic lib ├── fantastic └── fe 1 lib └── other lib 12 directories, 0 files How do I get a simple list with one path per line of all paths matching the patterns?
It seems like basic shell expansion just resolves the paths and separates them by space, without quoting the individual paths:
For example, what is this even matching?
$ echo "lib/"{"be","fe "*}" lib/"*"lib" lib/be lib/fantastic lib lib/fe 1 lib/other lib It could be: lib/be lib/fantastic, lib, lib/fe 1 and lib/other lib
Or: lib/be lib/fantastic lib and lib/fe 1 lib/other lib
Heck, it could even just be one long path: lib/be lib/fantastic lib lib/fe 1 lib/other lib
It seems impossible to tell if you don't know which space is a separator and which space is part of a path.
But equally challenging is the fact that you have to quote everything that contains a space, but at the same time you must not quote wildcards and the like.
I mean, I managed to hack something together, but I highly doubt this would actually take care of all possible cases:
echo 'lib/{be,fe *} lib/*lib' | sed -e 's/\([*,{}]\)/"\1"/g' -e 's/.*/"&"/' -e 's/""//g' Running it on my two patterns does appear to work:
$ echo -e 'lib/{be,fe *} lib/*lib\napps/app*' | sed -e 's/\([*,{}]\)/"\1"/g' -e 's/.*/"&"/' -e 's/""//g' | while IFS= read -r line; do bash -c "echo $line"; done lib/be lib/fantastic lib lib/fe 1 lib/other lib apps/app1 apps/app2 But again, where does a path start and where does it end?
And finally, I don't know how to get around using eval or bash -c. It seems kinda dangerous because a maliciously crafted pattern could basically wipe your system. For example a file pattern like bye && rm -rf ~ could delete your home directory.
man bash. It is a lot of text, but very worth reading at least once if you are going to use it. The pager usually used by man to read manual pages, less, has built-in search, which can be used for navigation. Readman lessto become familiar with it.