How to Validate User Access Permission to File/Directory in Linux using Shell Scripting

Hello There,

It’s been a while since i posted anything, and today i want to share how to validate user access permssion for files/directories in shell script. I needed it because i was doing some script which has somthing to do with file/directory permissions.

The function Will take file/directory path as argumnet and return yes or no. I hope that you will like it.

function validatePermissions(){

	PERMINFO=($(stat -c "%a %G %U" $1))
	PERMISSION=${PERMINFO[0]}
	GROUP=${PERMINFO[1]}
	OWNER=${PERMINFO[2]}

	if (( $PERMISSION & 0002 != 0 ))
	then
		#echo "Everybody has write access"
		echo yes
	elif (( $PERMISSION & 0020 != 0 ))
	then
		#echo "group has write access"
		gs=( $(groups $USER) )

		for g in "${gs[@]}"
		do
			if [ $GROUP == $g ]
			 then
				#echo "your group has access"
				echo yes
				break
			fi
		done

	elif (( $PERMISSION & 0200 != 0 ))
	then
		#echo "The owner has write access"
		[ $USER == $OWNER ] && echo "yes"
	else
		#echo "You don't have permission"
		echo no
	fi
}
Posted in Shell Scripting and tagged , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

Swedish Greys - a WordPress theme from Nordic Themepark.