0

I have a directory of files and I want to build an array of them and double quote them

file1.json file2.json

if I declare my array and do a directory listing:

declare -a array=("$(ls)")

echo ${array[@]}

I get

file1.json file2.json

how do I make the array so that when I output it - it is

"file1.json" "file2.json"

The Hamish
  • 31
  • 1
  • 4
    [Don't parse 'ls'](https://mywiki.wooledge.org/ParsingLs)! Use a wildcard (e.g. `declare -a array=(*)`) instead. Also, are you sure you want double-quotes around them? In general, putting shell syntax (like quotes) in your data doesn't work -- they get treated as part of the data, rather than as shell syntax. See: ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) – Gordon Davisson Sep 05 '20 at 04:45
  • the reason for the double quotes is the command I am feeding the array into requires them unfortunately – The Hamish Sep 05 '20 at 05:53

1 Answers1

2

I think your best bet is to use printf to print each one with double-quotes:

array=(*)
printf '"%s" ' "${array[@]}"
ruakh
  • 175,680
  • 26
  • 273
  • 307
  • thank you - how would I feed the output of that into a command? i.e. command "file1" and then it would do command "file2" where they are in the array we built? – The Hamish Sep 05 '20 at 08:41
  • @TheHamish: I'm sorry, I don't understand what you're trying to do. To help me understand . . . let's just pretend for a second that the files in your directory will always be named `file1` and `file2`, and that you don't need to use variables or anything because those are the exact filenames and you can hardcode them. If that were the case, what would be your hardcoded command? (I can then help you change that command to be non-hardcoded.) – ruakh Sep 05 '20 at 17:53