我有一个名为" test.sh"这将在名为" D1"的目录中创建24个备份文件。扩展名为.txt~,.bak和以#开头的12个文件。在这个测试工具中,我必须调用另一个名为" clean.sh"这将删除给定目录中的所有文件(在本例中为D1)。
这是我的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
这是clean.sh:
#!/bin/bash
#Need to pass a directory in as argument
for i in "$@"
do
echo file is: $I
done
我不确定如何将目录作为参数传入,并且在另一种方法中调用方法会让人感到困惑。谢谢!
答案 0 :(得分:1)
你的脚本是个不错的开始 touch命令可以不带参数D1,你的cleanup.sh调用需要一个参数。参数$ {PWD}由shell给出,在这种情况下很容易。 (你也可以给出像/ home / mina / test2 / D1这样的参数。)
脚本看起来像
!/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
现在是清理脚本
首先将$I
更改为$i
,变量名称区分大小写
使用for i in "$@"
循环访问参数(仅限dir的名称),
并且您想要浏览不同的文件名
请尝试以下替代方案:
# 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