Wednesday, 28 August 2013

Shell script: variable scope in functions

Shell script: variable scope in functions

I wrote a quick shell script to emulate the situation of xkcd #981
(without hard links, just symlinks to parent dirs) and used a recursive
function to create all the directories. Unfortunately this script does not
provide the desired result, so I think my understanding of the scope of
variable $count is wrong.
How can I properly make the function use recursion to create twenty levels
of folders, each containing 3 folders (3^20 folders, ending in soft links
back to the top)?
#!/bin/bash
echo "Generating folders:"
toplevel=$PWD
count=1
GEN_DIRS() {
for i in 1 2 3
do
dirname=$RANDOM
mkdir $dirname
cd $dirname
count=$(expr $count + 1)
if [ $count < 20 ] ; then
GEN_DIRS
else
ln -s $toplevel "./$dirname"
fi
done
}
GEN_DIRS
exit

No comments:

Post a Comment