Shell script: variable scope in functions -


i wrote quick shell script emulate situation of xkcd #981 (without hard links, symlinks parent dirs) , used recursive function create directories. unfortunately script not provide desired result, think understanding of scope of variable $count wrong.

how can make function use recursion create twenty levels of folders, each containing 3 folders (3^20 folders, ending in soft links top)?

#!/bin/bash echo "generating folders:" toplevel=$pwd count=1 gen_dirs() { in 1 2 3         dirname=$random         mkdir $dirname         cd $dirname         count=$(expr $count + 1)         if [ $count < 20 ] ;                 gen_dirs         else                 ln -s $toplevel "./$dirname"         fi done } gen_dirs exit 

try (amended version of script) — seems work me. decline test 20 levels deep, though; @ 8 levels deep, each of 3 top-level directories occupies 50 mb on mac file system.

#!/bin/bash echo "generating folders:" toplevel=$pwd gen_dirs() {     cur=${1:?}     max=${2:?}     in 1 2 3             dirname=$random         if [ $cur -le $max ]                     (             echo "directory: $pwd/$dirname"             mkdir $dirname             cd $dirname             gen_dirs $((cur+1)) $max             )         else             echo "symlink:   $pwd/$dirname"             ln -s $toplevel "./$dirname"         fi     done }  gen_dirs 1 ${1:-4} 

lines 6 , 7 giving names positional parameters ($1 , $2) passed function — ${1:?} notation means if omit pass parameter $1, error message shell (or sub-shell) , exits.

the parentheses on own (lines 13 , 18 above) mean commands in between run in sub-shell, changes in directory inside sub-shell not affect parent shell.

the condition on line 11 uses arithmetic (-le) instead of string < comparisons; works better deep nesting (because < lexicographic comparison, level 9 not less level 10). means [ command ok use instead of [[ command (although [[ work, prefer old-fashioned notation).


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -