boosh Account
boosh Account

Reputation: 23

How to ensure that root is the only UID 0 account?

I created two users test and test2 with UID of 0 and 1001. When I run this script the first condition is working which is $i != "root" so the output is that it prints both test and test2 but not root. However my second condition does not work.

#!/bin/bash

result="$(awk-F: '($3 == 0) { print $1 }' /etc/passwd)"
uid=$(stat --format=\%u /etc/passwd)

for i in $result
do 
    if [ $i != "root" ] && [[ "$uid" -eq 0 ]]; then
    grep ^i /etc/passwd | cut -d: -f1,3
fi
done

Upvotes: 1

Views: 482

Answers (1)

Fravadona
Fravadona

Reputation: 17290

Why not do it with awk from the start?

#!/bin/bash

users=( $(awk -F: '$3 == 0 && $1 != "root" {print $1}' /etc/passwd) )

if [[ ${#users[@]} != 0 ]]
then
    echo "non-root users with uid = 0: ${users[*]}"
fi

Or by returning a non-zero exit code with awk and saving the output at the same time:

#!/bin/bash

if users=($(awk -F: '$3==0 && $1!="root"{print $1;rc=1}END{exit !rc}' /etc/passwd))
then
    echo "non-root users with uid = 0: ${users[*]}"
fi

Upvotes: 1

Related Questions