How can I use a function which reads a variable?
Your function call is wrong:
Pdir($i) # this is wrong
In Bash, you call functions just like you would invoke binary executables, by writing their name as command and putting all arguments behind it, separated with spaces and not enclosed in any kind of brackets:
Pdir $i # this is correct, but not good
Note that you should almost always put variables into double quotes, to prevent them from getting split up and interpreted as multiple arguments if they contain spaces, so the optimal way to write it would be:
Pdir "$i" # this is how you do it
Another tiny mistake is that you need a space between the if
and the [
test.
You should also quote the variable again, and it is recommended to use the more modern $(...)
command substitution syntax instead of `...`
. Note that double quotes inside command substitution braces are allowed even if the substitution itself is surrounded by double quotes.
if [ "$(stat -c %F "${a[$i]}")" = "directory" ]
And instead of interpreting the output of ls
(Why not parse ls
?), it better to get an array of files and directories in the current directory e.g. using a shell glob:
a=(*)
Note that by default this only returns non-hidden files, i.e. everything that does not start with a dot. To also list hidden files and directories, enable the dotglob
shell option inside your script once first:
shopt -s dotglob
a=(*)
You can use shell glob */
to match only directories - thereby removing the need to to a separate directory check:
a=(*/)
Your first loop is unnecessary - all it does is count the elements in the array, which you can get using ${#a[@]}
In any case, you don't actually need to know the number of elements in order to loop over them - you can use
for i in "${a[@]}"; do
Pdir "$i"
done
Also printf is better than echo. So
#!/bin/bash
Pdir(){
printf '%s\n%s\n%s\n%s\n' \
" __ " \
"/---/ |" \
"| d |" \
"--------" \
"$1"
}
shopt -s nullglob
dirs=(*/)
for d in "${dirs[@]}"; do
Pdir "$d"
done
If you do want to process all files i.e. a=(*)
and test them explicitly, then rather than using stat
you can use a direct shell test
[ -d "$i" ]
(run help test
in the shell to see the options).