-1

Say I have the following in Bash:

FOO=/a/c*/d/
echo PATH=${FOO}:${PATH} >> .env

When I inspect the contents of the file .env the path still contains the wildcard. How can I ensure that the wildcard is expanded to the path, assuming there is only one match, so that the wildcard does not exist in the file when echoed?

Boon
  • 1,073
  • 1
  • 16
  • 42

2 Answers2

2

Make it an array assignment, and then use the first element of the array (to hold with the "assuming only one match"):

foo=( /a/c*/d/ )
echo "PATH=${foo[0]}:$PATH" >>.env

By contrast, if you don't specifically want the assumption, you can use ${array[*]} after setting : as the first character in IFS to expand correctly even in the case where there were multiple matches:

foo=( /a/c*/d/ )
IFS=:
echo "PATH=${foo[*]}:$PATH" >>.env

You could avoid needing to change IFS or pay the efficiency cost of starting a subprocess by expanding the list of paths to a separate variable:

printf -v path_prefix '%s:' /a/c*/d/
echo "PATH=${path_prefix}$PATH" >>.env
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

Perhaps also

foo=( /a/c*/d/ )
echo "PATH=$(IFS=:; echo "${foo[*]}"):$PATH" >> .env

so you don't have to restore IFS

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • There's an efficiency hit for the subshell that's worth pointing out -- sure, it's more work to need to restore IFS, but one gets some value for that work. – Charles Duffy Dec 21 '21 at 20:13
  • And if you _are_ going to have a subshell, you don't need an array at all. `echo "PATH=$(printf '%s:' /a/c*/d/)$PATH"` and you're done. Has the added benefit that if you `shopt -s nullglob` and there are no matches to the glob expression, the PATH doesn't get changed at all. – Charles Duffy Dec 21 '21 at 20:14
  • Good point about `printf` instead of array. – Diego Torres Milano Dec 21 '21 at 20:20