How to test if an attribute exists in a file with Bash?

Viewed 74

I'm trying to get this tested, but I'm not sure if the if is right

if [ $(lsattr /mnt/backup/*.* | grep i) ] ;
then
    echo "file  $_ has i attribute"; 
else
    echo "file $_ does not have i attribute"
fi

This is the lsattr on that directory:

----i----------------- /mnt/backup/Backup-Full_02-04-2022.7z

---------------------- /mnt/backup/test.7z

Thank you

1 Answers

With grep i you will also match file names containing i. Moreover, $_ is not set so its value is probably just the empty string. If you really want to use an if statement you also need a loop. And grep is not needed any more if you use the bash conditional expressions:

$ 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

If you can use awk instead of grep you can easily limit the search to the first word:

awk '$1 ~ "i"'

And you don't need any bash if or while loop any more, all this can be embedded in the awk script:

$ 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
Related