Search code examples
bashfile-attributes

Toggle file immutable


I which to make a simple little bash script that toggle some files (specifically my desktop icons so they don't move when they're not supposed to)

I have the command to make the files [im]mutable:

sudo chattr +i ~/.config/xfce4/desktop/icons*

However, to make the script toggle the state, i need to check the state, and act accordingly. But i'm not so good at the bash-codes and some googling doesn't bring up any solutions

the answer is probably something to do with 'lsattr' and 'grep' but i'm not sure in which form they should take...

(If the answer can be in the form of an if statement, that would be lovely :D )


Solution

  • Perhaps

    for file in ~/.config/xfce4/desktop/icons*
    do
         sudo chattr \
           $(lsattr "$file" | cut -c 5 | fgrep -q 'i' \
                && echo "-i" || echo "+i") \
           "$file"
    done
    

    Horribly inefficient, but …

    As an "if" —

      if lsattr "$file" | cut -c 5 | fgrep -q 'i'
      then
            # whatever
      fi