我有一个脚本可以找到文件夹中的文件,如果它们超过7天,则删除它们.但是,我有一点问题.
#!/bin/bash
BACKUPDIR=/home/vagrant/script/aerospike_backups
TIMESTAMP=$(date +%Y-%m-%d)
LOGPATH=/tmp/logs.txt
ADMINACC=email@example.com
EMEIL=rybka@gl.com
#Let's check existing backups, and if it's older than 7 days delete
find_old () {
if [ -z $(find $BACKUPDIR -mtime +7 -print ) ]
then
return 10
else
find $BACKUPDIR -mtime +7 -delete && echo "Backups deleted at $HOSTNAME on $TIMESTAMP" > $LOGPATH
fi
}
Run Code Online (Sandbox Code Playgroud)
如果我从终端使用./scriptname执行带有$ BACKUPDIR的脚本,那么输入echo $?shell按预期输出10个代码,因为没有7天的文件或根本没有文件.
但是在我添加更多如果条件之后
if [[ $(find_old | echo $?) -gt 0 ]]
then
echo "Script return error code"
else
echo "all is ok"
Run Code Online (Sandbox Code Playgroud)
脚本给了我输出all is ok,但它真的不应该?怎么了?
将找到的文件存储在一个数组然后删除它们,而不是调用find两次更好- 这样,我们保证删除我们找到的确切文件集,并且效率更高.
find_old() {
while read -r -d '' file; do # read the output of find one file at a time
files+=("$file") # append to the array
done < <(find "$BACKUPDIR" -mtime +7 -print0) # generate NUL separated list of files
if ((${#files[@]} == 0)); then
# no files found
return 10
else
printf '%s\0' "${files[@]}" | xargs -0 rm -f --
fi
}
Run Code Online (Sandbox Code Playgroud)
然后,将您的功能称为:
find_old; exit_code=$?
if ((exit_code > 0)) {
echo "Script returned error code $exit_code"
else
echo "All is OK"
fi
Run Code Online (Sandbox Code Playgroud)
我已在您的代码中修复了一些问题:
find "$BACKUPDIR"而不是find $BACKUPDIRif [[ $(find_old | echo $?) -gt 0 ]]不是检查函数退出代码的方法; 你需要$?直接检查也可以看看:
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |