Home > Software engineering >  I called a Function recursively using shellscript,but the function doesnt accept the arguments while
I called a Function recursively using shellscript,but the function doesnt accept the arguments while

Time:02-03

I am trying to print the sub-file and sub directories of a Specific file. The case is, I will be giving the location of the root-folder directly.First it should print the files and directories of the root-folder,in-case of files , it should only print the name of the file and return .In-case of folders, it should print the folder name and traverse through that sub- folder and print the files and folders present in it . So the case is, if it is file then print the name of file and leave else if it is a folder present ,recursively traverse through the folder and print the contents inside and if you find sub-folder in this folder, again recursively traverse it till you find no folder present. I need to execute in shell-script language

I had writen the sample code for this in java. This is the code logic. I am trying the same logic in shellscript but whenever I call the function recursively,it runs a infinite loop in shell script

Java code :

 import java.io.File;
 import java.nio.file.Files;
 public class Recursion 
 {
   public static void fileRecursive(File root)
   {
     System.out.println(root.getName());
     if(root.isFile()) 
     {
      return;
     }
     else
     {
      File[] files = root.listFiles();
      for(File file : files)
      {
       fileRecursive(file);
      }
     }
   }
 public static void main(String args[])
 {
  File directoryPath = new File("/home/keshav/Main");
  System.out.println("Root Folder : " directoryPath.getName());
  fileRecursive(directoryPath);
}

}

 Shell-Script Code:


 FileTraverse()
 {
   path=$dirname
   if [ -f "$path" ];  
    then 
       return;
   else 
   for dir in `ls $dirname`;
    do
    FileTraverse $dir
    done
   fi         
  }

 echo "Enter Root directory name"
 read dirname
 FileTraverse $dirname

CodePudding user response:

Analyzing your program, we can see:

  1. You assign a value to the variable dirname only once (outside the function in the read statement), but never assign a new value for it. Every invocation of the function (including the recorsive ones) use the same value for this variable.

  2. You call your function by passing a parameter, but you never actually use this parameter.

Solution: Inside the function do a

path=$1

as a first statement and in the function body, replace each occurance of dirname by path.

  • Related