TASK
I am trying to pass a pathname/filename to awk in order to take advantage of its field seperator functionality. I want to parse a pathname/filename to see if it is within a user directory in a system. Example paths:
Absolute Paths:
/home/students/username # VALID
/home/staff/username # VALID
/home/students/username/anythingElse # VALID
/home/staff/username/anythingElse # VALID
/home/notAccountStorage/anythingElse # INVALID
Relative Paths (For Exmaple, where the pwd/current is /home/student/user/courseFiles):
../ # VALID /home/student/user
../otherDir # VALID /home/student/user/other
../. # VALID /home/student/user
../.. # INVALID /home/student
../../otherDir # INVALID /home/student/otherDir
CODE
My thoughts were to check if the string begins with a '/' then process for absolute path, else process for relative path.
AWK code along the lines of:
awk -F="/" ' BEGIN { directoryAccentCount=0 \
isValid=$FALSE; \
} \
{ \
# If the string starts with a "/", path is absolute \
if ( $0 ~ /^\// ) { \
# If either Student/Staff && Number of Fields must be great than 2 \
if ( ($2 == "student" || $2 == "staff") && NF > 2 ) isValid=$TRUE \
} else { \
# Path is relative \
for (i = 1; i <= NF; i++) { \
# Count how many directories the User wants to ASCEND towards ROOT \
if ( $i ~ /\.\./ ) { directoryAccentCount++ } \
# If the difference between the Number of Fields and \
# the Accent Count is greater than 2, isValid=$TRUE \
difference=(NF - $directoryAccentCount) \
if ( $difference > 2 ) isValid=$TRUE \
} \
} \
END { print $0 ":" $isValid }' << HERE $providedPath
HERE
ERROR
I have tried variations of the above code, but awk keeps attempting to follow the file path, open the file, and process the file's text. I want to process the path itself.
awk: fatal: file `noCopyDir1' is a directory
Simplified logic to determine directory ascent/decent only in the case of relative paths. The awk script takes advantage of looping through the fields one by one and returns a negative value when moving towards the root and a positive value when moving away from root.
This is an essential step in determining whether a file path advances outside of user accounts in a system or remains within a user directory, which is how I am applying the script, however, it can be used in many other cases.