The error comes from the fact that $( echo id -g $user )
will be expanded into the words id -g username
. This can not be compared to 101
since the expansion is unquoted.
To compare the output of id -g "$user"
(note the double quotes), use
if [ "$( id -g "$user" )" = "101" ]
Within [ ... ]
you should use a single =
to do string comparison. In shells that have [[ ... ]]
you may use ==
:
if [[ $( id -g "$user" ) == "101" ]]
Here, the quoting of the command substitution is not required, but it is if you use [ ... ]
.
The idiomatic way to do this sort of task is not to store the output of the who
pipeline in a variable, but to pass it directly to the loop:
who | awk '{ print $1 }' | sort -u | while read user; do if [ "$( id -g "$user" )" = "101" ]; then echo 'Got it' fi done
$(id -g $user)
? Not sure why you need theecho
there. The result of the command should be sufficient, I think.who=...
;
to close thefor
loop after thefi