Shell Script To Run Same Command In Directories & SubDirectories

July 15, 2013 | By
| Reply More

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

Filed Under : SHELL SCRIPTS

Free Linux Ebook to Download

Leave a Reply

Commenting Policy:
Promotion of your products ? Comment gets deleted.
All comments are subject to moderation.