I'm trying to write a bash script that inverts the given file's group permissions. For example:
if file.txt had the permissions -rw-r--r--
, it would be inverted to -rw--wxr--
if file.txt had the permissions -rw--w-r-x
, it would be inverted to -rw-r-xr-x
I've done something similar to this in python before, where I used the XOR bitwise operator ^
to invert the execute permissions.
I can't seem to figure out the proper way of doing this in bash The filename will be provided as a command line argument
CodePudding user response:
Would you please try the following:
#!/bin/bash
fname=$1 # filename is given at the command line
perm="0$(stat -c %a "$fname")" # permissions in oct such as 0644
iperm=$( printf "0%o" $(( perm ^ 070 )) )
# invert the group permissions such as 0634
chmod "$iperm" "$fname" # update the file status