我正在尝试对此进行测试,但我不确定if是否正确
if [ $(lsattr /mnt/backup/*.* | grep i) ] ;
then
echo "file $_ has i attribute";
else
echo "file $_ does not have i attribute"
fi
这是该目录上的lsattr:
----i----------------- /mnt/backup/Backup-Full_02-04-2022.7z
---------------------- /mnt/backup/test.7z
谢谢
使用grep i
还可以匹配包含i
的文件名。此外,$_
没有设置,因此它的值可能只是空字符串。如果你真的想使用if
语句,你还需要一个循环。如果使用bash
条件表达式,则不再需要grep
:
$ lsattr /mnt/backup/*.* | while read -r attr name; do
if [[ "$attr" == "*i*" ]]; then
echo "file $name has i attribute"
else
echo "file $name does not have i attribute"
fi
done
file /mnt/backup/Backup-Full_02-04-2022.7z has i attribute
file /mnt/backup/test.7z does not have i attribute
如果你可以使用awk
而不是grep
,你可以很容易地将搜索限制在第一个词:
awk '$1 ~ "i"'
并且您不再需要任何bash
if
或while
循环,所有这些都可以嵌入到awk
脚本中:
$ lsattr /mnt/backup/*.* | awk -vs1=" has " -vs2=" does not have "
'{print $2 ($1 ~ "i" ? s1 : s2) "i attribute"}'
file /mnt/backup/Backup-Full_02-04-2022.7z has i attribute
file /mnt/backup/test.7z does not have i attribute