Bash: 使用目录作为变量
Bash: Use directory as variable
我正在写一个脚本来检查是否真的有一个目录有内容和正常大小,看看是否有一个目录早于 36 小时,如果没有它应该提醒我。
但是我在使用目录作为变量时遇到了问题。
当我执行脚本时 returns: ./test.sh: line 5: 1: No such file or directory
。
我也试过 ALLDIR=$(ls /home/customers/*/
但返回了同样的错误。
我做错了什么?下面是脚本。
提前致谢!!
#!/bin/bash
ALLDIR=$(find * /home/customers/*/ -maxdepth 2 -mindepth 2)
for DIR in ${ALLDIR}
do
if [[ $(find "$DIR" -maxdepth 1 -type d -name '*' ! -mtime -36 | wc -l = <1 ) ]]; then
mail -s "No back-ups found today at $DIR! Please check the issue!" test@example.com
exit 1
fi
done
for DIR in ${ALLDIR}
do
if [[ $(find "$DIR" -mindepth 1 -maxdepth 1 -type d -exec du -ks {} + | awk ' <= 50' | cut -f 2- ) ]]; then
mail -s "Backup directory size is too small for $DIR, please check the issue!" test@example.com
exit 1
fi
done
首先,要遍历固定深度的所有目录,请使用:
for dir in /home/customers/*/*/*/
以斜杠结尾的模式 /
将只匹配目录。
注意$dir
是一个小写的变量名,不要使用大写的,因为它们可能会与shell internal/environment变量冲突。
接下来,你的条件有点不对 - 你不需要在这里使用 [[
测试:
if ! find "$dir" -maxdepth 1 -type d ! -mtime -36 | grep -q .
如果找到任何东西,find
将打印它并且 grep
会安静地匹配任何东西,因此管道将成功退出。开始时的 !
否定条件,因此 if
分支只会在这种情况没有发生时才会被采用,即当没有找到任何东西时。 -name '*'
是多余的。
您可以对第二个 if
执行类似的操作,删除 [[
和 $()
并使用 grep -q .
测试任何输出。我想 cut
部分也是多余的。
我正在写一个脚本来检查是否真的有一个目录有内容和正常大小,看看是否有一个目录早于 36 小时,如果没有它应该提醒我。
但是我在使用目录作为变量时遇到了问题。
当我执行脚本时 returns: ./test.sh: line 5: 1: No such file or directory
。
我也试过 ALLDIR=$(ls /home/customers/*/
但返回了同样的错误。
我做错了什么?下面是脚本。
提前致谢!!
#!/bin/bash
ALLDIR=$(find * /home/customers/*/ -maxdepth 2 -mindepth 2)
for DIR in ${ALLDIR}
do
if [[ $(find "$DIR" -maxdepth 1 -type d -name '*' ! -mtime -36 | wc -l = <1 ) ]]; then
mail -s "No back-ups found today at $DIR! Please check the issue!" test@example.com
exit 1
fi
done
for DIR in ${ALLDIR}
do
if [[ $(find "$DIR" -mindepth 1 -maxdepth 1 -type d -exec du -ks {} + | awk ' <= 50' | cut -f 2- ) ]]; then
mail -s "Backup directory size is too small for $DIR, please check the issue!" test@example.com
exit 1
fi
done
首先,要遍历固定深度的所有目录,请使用:
for dir in /home/customers/*/*/*/
以斜杠结尾的模式 /
将只匹配目录。
注意$dir
是一个小写的变量名,不要使用大写的,因为它们可能会与shell internal/environment变量冲突。
接下来,你的条件有点不对 - 你不需要在这里使用 [[
测试:
if ! find "$dir" -maxdepth 1 -type d ! -mtime -36 | grep -q .
如果找到任何东西,find
将打印它并且 grep
会安静地匹配任何东西,因此管道将成功退出。开始时的 !
否定条件,因此 if
分支只会在这种情况没有发生时才会被采用,即当没有找到任何东西时。 -name '*'
是多余的。
您可以对第二个 if
执行类似的操作,删除 [[
和 $()
并使用 grep -q .
测试任何输出。我想 cut
部分也是多余的。