1

Trying to create a bash script to check for users with no home directories:

homeless=()
cat /etc/passwd | awk -F: '{ print $1 " " $3 " " $6 }' | while read user uid 
dir; do 
if [ $uid -ge 1000 -a ! -d "$dir" -a $user != "nfsnobody" ]; then 
homeless+=("$user, ")
fi 
done

echo ${homeless[@]}

Does anyone know why my array is empty, even though the script produces an output?

If I echo $user in the while loop like this:

if [ $uid -ge 1000 -a ! -d "$dir" -a $user != "nfsnobody" ]; then 
    echo "$user, "
fi 
done

I can achieve an output of:

#./script.sh
testuser1, testuser2,
REDBEAN
  • 21
  • 5
  • What do you mean? – REDBEAN Nov 19 '17 at 18:30
  • Added some info. the condition evaluates to true twice, but nothing is added to the array. – REDBEAN Nov 19 '17 at 18:35
  • 1
    Because of what's explained [in BashFAQ/024: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?](http://mywiki.wooledge.org/BashFAQ/024). Write your code as: `while read ......; done < <(awk -F: '{ print $1 " " $3 " " $6 }' /etc/passwd)`. You can also avoid `awk` altogether and only use Bash. – gniourf_gniourf Nov 19 '17 at 18:36
  • 1
    Something like this: `homeless=(); while IFS=: read user _ uid _ _ dir _; do if [[ $uid -ge 1000 && ! -d $dir && $user != nfsnobody ]]; then homeless+=( "$user" ); fi; done < /etc/passwd; printf '%s\n' "${homeless[@]}"` – gniourf_gniourf Nov 19 '17 at 18:42
  • @gniourf_gniourf thanks so much man, that worked perfectly! – REDBEAN Nov 19 '17 at 19:05

0 Answers0