The Bash for loop
To achieve a recursive loop through directories, we will use bash loops, specifically, a for a loop.
The for loop is a common type of loop in Bash and other programming languages. It iterates over a given list of items/options until and executes a set of commands.
The general syntax for the for loop command is:
do
[COMMAND]
done;
Here is an example of a bash loop is:
for i in {0..10}
do
echo ‘$’
done
The above loop prints values from 0 to 10.
Bash User input
Next, we need to prompt the user for a valid directory to loop through. To accept user input, we use the echo command in Bash.
For example:
echo “Enter the directory”
read dir
cd $dir
echo “Now in /etc”
Move Files (Bash Script)
With the concepts of loops and user input out of the way, we can put our shell together. The first operation is to find files recursively with specific extensions and move them.
Here is a sample script for that:
echo “Enter dir”
read dir
echo “Enter destination”
read dest
for i in $(find $dir -name '*.log');
do
mv -v $i $dest
done;
The script will ask the user for a directory and then search for a specific extension. It will then move the files to the specified destination.
Delete files
The script above can also be modified to delete files instead of moving them. An example is as
echo "Enter dir"
read dir
for i in $(find $dir -name '*.log');
do
rm -rf $i
done;
Print Files
To print the files in a directory, use the script as:
echo “Enter dir”
read dir
cd $dir
for i in $(find $dir -type f);
do
echo $i;
done;
Conclusion
The above are example scripts you can use to loop directories and perform a specific action. It is good to note there are tools developed to perform such tasks, but a script is a good way to go if you can’t find an appropriate tool.
from Linux Hint https://ift.tt/3hEfTLH
0 Comments