1

This is my script

[root@localhost scripts]# cat nested.sh
#!/bin/ksh

echo Enter the level of nesting
read lev
echo Enter the directory \( Enter the Absolute Path\)
read path
echo Enter the directory name
read $dirname
cd $path
for((i=1;i<=$lev;i++));
 do
  mkdir '$dirname$i'
  cd '$dirname$i'
 done
echo $dirname$i

Assume that towards the end the value of $dirname is "fold" and value of $i is "5".
I was expecting the last statement echo $dirname$i to print fold5
but instead it only prints 5.

Can someone please explain how to print "fold5" ?
Also can someone please explain why it only printed 5 for me ?

  • It looks better to get read to show the prompt: read dirname?"Enter the directory name: " – glenn jackman Aug 26 '15 at 20:40
  • Thanks @glenn jackman, will definitely start following this :) – Dhiwakar Ravikumar Aug 27 '15 at 4:41
2

you have a typo on line 8 of your script, it should be: read dirname That's the reason you only get '5' printed, because $dirname is empty.

What is happening is that when you do read $dirname the shell expands '$dirname' to it's value which is empty.

Also on a side note, always use double-quotes when enclosing variables.

Revised script:

#!/bin/ksh

echo Enter the level of nesting
read lev
echo Enter the directory \( Enter the Absolute Path\)
read path
echo Enter the directory name
read dirname
cd $path
for((i=1;i<=$lev;i++));
 do
  mkdir "$dirname$i"
  cd "$dirname$i"
 done
echo "$dirname$i"
  • And when you call read with no variable, the user's data is stored in the $REPLY variable: to demonstrate: read; echo "$REPLY" – glenn jackman Aug 26 '15 at 20:37
  • Thanks glenn jackman & Dalvenjia, silly mistake on my part – Dhiwakar Ravikumar Aug 27 '15 at 4:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.