(2013-09-04) Reading Checking And Changing Permissions With Bash

Just a quick update this time; I was looking for a way to check the permissions of a file are that which is expected, which is actually really easy to do (if you have stat).

I thought, wh ynot add this as a function to bashlib (of course!) and also add a way of simply reading the current permissions and also setting new ones (so you could check if the file has the expected permissions, change the permissions, and then return the new permissions to make sure everything went okay).

~~~~
function perm[check] () {
        [[ ! ${1} ]] && _e=0 && return 0
        declare -i f
        f=$(find ${1} -name ${2} -perm ${3} | wc -l)
        [[ ${f} == 1 ]] && _p=1 || _p=0
}

function perm[set] () {
        [[ ! ${1} ]] && _e=0 && return 0
        find "${1}" -name "${2}" -exec chmod ${3} {} \;
        perm[check] "${1}" "${2}" "${3}"
}

function perm[get] () {
        [[ ! ${1} ]] && _e=0 && return 0
        _pe=$(stat "${1}${2}" -c %a)
}
~~~~

Check and set both require [CONTAINING_DIRECTORY] [FILE/DIRECTORY] [PERMISSIONS]. Get just requires the first two (obviously). Set also runs check as the last command which then returns a 1 or 0 in the _p variable (to confirm if the set went through).

This could easily be used to automatically modify things with incorrect permissions.

~~~~
dir="./"
files=("testing1" "testing2" "testing3" "testing4")
perm="600"
for file in ${files[@]}; do
        [[ ! -f "${dir}${file}" ]] && echo "Error: File '${dir}${file}' not found." && continue
        perm[check] ${dir} ${file} ${perm}
        perm[get] ${dir} ${file}
        [[ ${_p} == 0 ]] && perm[set] ${dir} ${file} ${perm}
        [[ ${_p} == 0 ]] && echo "Error: Cannot set '${perm}' permissions on '${dir}${file}'. Still has '${_pe}'."
        continue
done
~~~~

The files array could be generated from elsewhere.

As usual, this was implimented into bashlib.

Also, most of my helper scripts have now been updated to the new function format and are avaliable on Github.