abdi abdi - 2 months ago 15
Bash Question

BASH - printing contents of a directory in reverse

Currently, I'm working on this homework assignment:


Write a Bash script,
reverse.sh
, which reverses the contents of a directory passed as a parameter. Assuming
/my/dir
contains
cache cron games lib log run tmp
, your program
reverse.sh /my/dir
will return
tmp run log lib games cron cache
. Use an array and two functions:
main()
and
reverse()
. You will manually manipulate the list as we did today. DO NOT use the built-in command
sort -r
.


For now, I've decided to use one function to get proper output first, that's not my problem. This is my script so far:

function main(){
p=$1
cd $p
reverse $p
}

function reverse(){
local p2=$1
local ARRAY=()
local count=0
for entry in $p2*
do
((count++))
ARRAY+=($entry)
done
while [ $count -gt -1 ]; do
echo ${ARRAY[$count]}
((count--))
done
}
main


However, I get the same output every time, no matter what directory I add as a parameter when running the script.

Answer

p=$1 will not work because main is not being called with any arguments (the args are not automatically passed from the command line to the function). Fix is to pass all the command line args to the function:

    main $@