In the following script, I am using bash to check whether users own their home directories as part of the CIS CentOS 8 Benchmark (6.2.8).
#!/bin/bash grep -E -v '^(halt|sync|shutdown)' /etc/passwd | awk -F: '($7 != "'"$(which nologin)"'" && $7 != "/bin/false") { print $1 " " $6 }' | while read user dir; do if [ ! -d "$dir" ]; then echo "The home directory ($dir) of user $user does not exist." else owner=$(stat -L -c "%U" "$dir") if [ "$owner" != "$user" ]; then echo "The home directory ($dir) of user $user is owned by $owner." fi fi done I am trying to print something if there are no errors using a global variable. The following is my attempt at it:
correct=true grep -E -v '^(halt|sync|shutdown)' /etc/passwd | awk -F: '($7 != "'"$(which nologin)"'" && $7 != "/bin/false") { print $1 " " $6 }' | while read user dir; do if [ ! -d "$dir" ]; then echo "The home directory ($dir) of user $user does not exist." correct=false else owner=$(stat -L -c "%U" "$dir") if [ "$owner" != "$user" ]; then echo "The home directory ($dir) of user $user is owned by $owner." correct=false fi fi done if [ "$correct" = true ]; then echo "Non-compliance?: No" echo "Details: All users own their home directories." echo fi However, the global variable, correct, will not change regardless of what happens in the while loop because it is in multiple sub-shells. I read up about this and noticed people using "here strings" so that the while loop will not be in a sub-shell. However, for my case I have multiple pipes (possibly might even add more for other scripts), so I don't really know how to make it do what I want here.
How can I get results information out of a loop so I can display summary information after the loop completes when the loop is executed in a sub-shell?
correctglobal variable and some output if compliant.shopt -s lastpipewhich allows to run last command of pipe in the current shell.shopt -s lastpipecommand do?