Please use ***
[code][/code] tags*** around your code and data, to preserve formatting and to improve readability. Please do
not use quote tags, colors, or other fancy formatting.
I have never seen
opendir/readdir either, and they certainly don't exist in
bash. There are C library functions with those names, but I can't find them as stand-alone commands anywhere on my system or in the apt repositories. Could you explain what they are and where you learned about them?
In any case, the OP code does not actually work at all. The only reason you're getting the output you do is due to this line:
This line first sets the variable "
files" to the literal text string "
readdir"; and then (since it prefixes it directly) passes that value to the environment of the
dir command before executing it, instead of setting it globally.
dir is simply an alias for
ls, so all your script is doing is listing the contents of the current directory.
As for colucix's suggestion here:
Code:
files=( $(readdir "$dir") )
Command substitution suffers the same issue of word-splitting that variable substitution does, so files with whitespace in them will not be stored properly in the array.
http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes
The proper way to access files is generally with simple
globbing. globbing filename expansion happens at the end of the parsing order, after word-splitting, and so isn't subject to that weakness. You can use it to populate an array, or directly in a loop, as in suicidaleggroll's example.
Code:
cd directory
files=( * )
for file in "${files[@]}"; do
echo "$file"
done