Reputation: 159
I have a test harness called "test.sh" that will create 24 backup files in a directory called "D1" with extensions .txt~, .bak, and 12 files that start with #. In this test harness I have to call another method called "clean.sh" that will delete all the files in the given directory (in this case D1).
This is my test.sh:
#!/bin/bash
#Create new directory called D1
mkdir D1
#cd into D1
cd ./D1
#Create 12 backup files .bak in D1 (using for loop)
for i in `seq 1 12`;
do
#echo $I
touch file$i.bak D1
done
#Create 12 backup files .txt~ in D1 (using set)
touch {a..l}.txt~ D1
#Create 12 files prefix # in D1 (using while loop)
COUNTER=0
while [ $COUNTER -lt 12 ]; do
touch \#$COUNTER.txt D1
let COUNTER=COUNTER+1
done
#Once finished creating backup files in all 3 categories, do an ls -l
ls -l
#Invoke clean method here
./cleanUp.sh
#Do final ls - l
ls - l
This is clean.sh:
#!/bin/bash
#Need to pass a directory in as argument
for i in "$@"
do
echo file is: $I
done
I'm not sure how to pass in a directory as an argument and calling a method in another method is confusing. Thanks!
Upvotes: 1
Views: 273
Reputation: 20012
Your script is a nice start.
The touch commands can do without the parameter D1, your cleanup.sh call needs a parameter. The parameter ${PWD} is given by the shell, thats easy in this case.
(you can also give a parameter like /home/mina/test2/D1).
The script will look like
!/bin/bash
#Create new directory called D1
mkdir D1
#cd into D1
cd ./D1
#Create 12 backup files .bak in D1 (using for loop)
for i in `seq 1 12`;
do
#echo $I
touch file$i.bak
done
#Create 12 backup files .txt~ in D1 (using set)
touch {a..l}.txt~
#Create 12 files prefix # in D1 (using while loop)
COUNTER=0
while [ $COUNTER -lt 12 ]; do
touch \#$COUNTER.txt
let COUNTER=COUNTER+1
done
#Once finished creating backup files in all 3 categories, do an ls -l
ls -l
#Invoke clean method here
./cleanUp.sh ${PWD}
#Do final ls - l
ls - l
Now the cleanup script.
First change $I
into $i
, the variable name is case sensitive.
With for i in "$@"
you loop through the parameters (only the name of the dir),
and you would like to go through the diffferent filenames.
Try the following alternatives:
# Let Unix expand the * variable
for i in $1/*; do
# Use a subshell
for i in $(ls "$@"); do
# use a while-loop
ls $@ | while read i; do
# use find and while
find "$1" -type f | while read i; do
# use find and -exec
find "$1" -type f -exec echo File is {} \;
# use find and xargs
find "$1" -type f | xargs echo File is
Upvotes: 1