gpt4 book ai didi

linux - Bash 脚本删除给定目录中的备份文件并以另一种方法调用该脚本?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:53:08 25 4
gpt4 key购买 nike

我有一个名为“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

我不确定如何将目录作为参数传递并在另一个方法中调用一个方法令人困惑。谢谢!

最佳答案

您的脚本是一个不错的开始。
触摸命令可以不带参数 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 "$@" 循环遍历参数(仅目录名称),并且您想查看不同的文件名。
尝试以下替代方案:

# 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

关于linux - Bash 脚本删除给定目录中的备份文件并以另一种方法调用该脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29154344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com