0

I'd like to retrieve the result of a

echo $1/*.pem 

and put the result in a array.

I tried:

a = echo $1/*.pem | grep pem  *

or

a = echo $1/*.pem

It fails.

When I do:

echo $1/*.pem 

it display the good result

/opt/tmp/a.pem /opt/tmp/ab.pem
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
aez
  • 27
  • 1
  • 6
  • Possible duplicate of [Bash: loop through all the files with a specific extension](https://stackoverflow.com/questions/14505047/bash-loop-through-all-the-files-with-a-specific-extension) – Kind Stranger Jun 26 '17 at 17:18

1 Answers1

1

You can let bash do the expansion and use parenthesis to cast an array without the use of echo:

a=( "$1"/*.pem )
echo "${a[@]}"

You can use echo but you'll have to use command substitution to reassign the output of the echo command to the array, and you will have problems if you have spaces in the name of your path:

a=( $(echo $1/*.pem) )
MauricioRobayo
  • 2,207
  • 23
  • 26
  • 1
    I'd also recommend double-quoting the array when you use it (e.g. `echo "${a[@]}"`) -- again, this is to avoid problems with spaces or other shell metacharacters in the filenames. Double-quoting variable references is almost always a good idea in shell scripts. – Gordon Davisson Jun 27 '17 at 01:02
  • @GordonDavisson Thanks for the useful feedback, I have updated my answer with your recommendation. – MauricioRobayo Jun 27 '17 at 01:35
  • But a=( $(echo $1/*.pem) ) works retrieve only the first file in the directory – aez Jun 27 '17 at 08:03
  • @aez Both should work; make sure you're testing them correctly. For the first, the `echo` is a second command and must be on a separate line from the assignment (or at least separated with a semicolon, like this: `a=( "$1"/*.pem ); echo "${a[@]}"`. Fir the second, make sure you use `"${a[@]}"` to get all elements of the array -- if you use `$a`, you only get the first element. – Gordon Davisson Jun 27 '17 at 21:02