shell script to list files in a directory recursively
How to write a shell script to list files in a directory recursively. Linux shell scripts are group of commands. Usually we print list of files and directory in present working directory. To list files and directory we use ls command. ‘ls -R’ commands recursively list all files.
shell script to list files in a directory recursively based on ls command
- Create a file list_files.sh
- Write following code
#!/bin/bash for file in $(ls -R) do echo $file done
- Make list_files.sh executable using command ‘chmod +x list_files.sh
- Run your script using command ‘sh list_files.sh’
- You will see output like below
bo@bo-Inspiron-N5150:~/myproject/sample/gtk$ sh list_files.sh .: go list_files.sh mediapla.c mediapla.c~ wikiplayer ./go: ann
The output of shell script program list_files.sh contains a “.”. The dot (.) means current directory. The above scripts will print all files and directories. we can use find command to list all files in a directory recursively. See below example shell scrips.
#!/bin/bash for file in $(find . -type f) do echo $file done
It will list all files from current working directory and subdirectory .find . -type f ,passing -type f ignores the name of directory. There are many other way to list files. Try to learn more option from linux manual page for find and ls command using ‘man ls’ command.