0

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.

IgorD
  • 155
  • 1
  • 8

2 Answers2

0

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.

Moritz Sauter
  • 167
  • 1
  • 11
  • Any way to put full path into each element? – IgorD Sep 07 '17 at 18:12
  • You mean that the array looks like this: "/var/db/TokenCache/config"? If it is really necessary I would suggest you look into [that answer on SO](https://stackoverflow.com/questions/27340307/list-file-using-ls-command-in-linux-with-full-path) – Moritz Sauter Sep 07 '17 at 20:04
  • But keep in mind that spaces in your path will break the array. Personally I would prefer to store the path in a variable (as you have to supply it to the `ls` call you have it anyway) and add it just in time when you use one of the elements in `files` – Moritz Sauter Sep 07 '17 at 20:06
  • I did try it that way, but can't make it work in combination with the array. Can you please edit the code above so it prints the full path and then I can accept it as an answer if it works? – IgorD Sep 07 '17 at 20:47
  • Yes, thanks. I have other problems now but I'll probably start another question. – IgorD Sep 08 '17 at 15:29
0

The glob expansion happens in the shell, so you need a shell instance that is running as a user with the correct permissions.

sudo bash -c 'files=(/var/db/*); printf "%s\n" "${files[@]}"'
chepner
  • 497,756
  • 71
  • 530
  • 681