Shell Script To Run Same Command In Directories & SubDirectories

This linux shell script allows system administrator to run same command in all folders and sub-folders. For example system administrator need to have list of all file or need to rename or delete etc.

Linux Shell Script

#!/bin/bash
# we ask user to enter directory from where to start
echo -n "Please enter directory from where to run command: "
#we read inputed directory
while read dir
do
#we check if input empty
test -z "$dir" && {
#if input empty – we ask user once more enter directory
echo -n "Please enter directory: "
continue
}
#if not empty – we go to next commands
break
done
#we ask user to input needed depth
echo -n "Please enter maxdepth, press enter to run in all subdirs: "
We write imput to variable
read maxdepth
#we ask user to input command to run
echo -n "Please enter command to run: "
#we read input
while read command
do
#we check input, since command can't be empty
test -z "$command" && {
#if input empty re-ask user to input
echo -n "Please enter command: "
continue
}
break
done
#we store directory list in temp file
DirList=/tmp/dirlist.tmp
#we check value that user input on depth
if [ x$maxdepth = "x" ];
#if no input – we will go recursively down
then
findpar=""
else
#if user put value to depth – we will use it
findpar=" -maxdepth $maxdepth"
fi
#We find all directories inside inputed directori
find $dir $findpar -type d > $DirList
#Writing directory list to variable
Dirs=`cat $DirList`
#processing each directory
for dirname in $Dirs
do
#we go to directory
cd $dirname
#we run command
$command
done

Shell Script Output

# ./subdir.sh
Please enter directory from where to run command: /tmp
Please enter maxdepth, press enter to run in all subdirs:
Please enter command to run: ls
CRX_75DAF8CB7768
dirlist.tmp
ditlist.tmp
gedit.yevhen.3535304311
kde-yevhen
keyring-d1AULx
ksocket-yevhen

Bobbin Zachariah 8:09 am

About Bobbin Zachariah

Founder of LinOxide, passionate lover of Linux and technology writer. Started his career in Linux / Opensource from 2000. Love traveling, blogging and listening music. Reach Bobbin Zachariah about me page and google plus page.

Author Archive Page

Have anything to say?

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.