Search code examples
bashmacosls

On OSX, how do I put filenames of a restricted system directory into an array?


When I enter in terminal

files=(/var/db/*); printf '%s\n' "${files[@]}"

and run it, I get a list of files in that folder, but going into restricted TokenCache dir does not give anything:

files=(/var/db/TokenCache/*); printf '%s\n' "${files[@]}"

This command gives me back /var/db/TokenCache/* and not files/folders inside. Is there any way to make it work inside restricted folders as sudo ls and even sudo rm work inside? For example:

sudo ls -la /var/db/TokenCache

shows its content, namely two folders config and tokens.


Solution

  • The answer could be something like this:

    files=($(sudo ls "/var/db/TokenCache"))
    printf '%s\n' "${files[@]}"
    

    But this is only safe under the assumption, that the specified folder (TokenCache in this case) only contains elements without any spaces in their name.

    If you want to get the full path out of the array for each file I would suggest something like this:

    directory="/var/db/TokenCache"
    files=($(sudo ls "${directory}"))
    printf "${directory}/%s\n" "${files[@]}"
    

    Notice that the ' changed to " in the format specifier of the printf call. Thats necessary to have variable expansion by the shell.