Check if uid numbers in /etc/passwd are in a certain range and not already used, with nested ifs

78 Views Asked by At

I am trying to check the uid's that are already used and in within a range from 1000 to 60000, with nested if conditions but only the range condition works. Also it prints the $hpass content. Any ideas how to improve the code?

Thanks in advance for any suggestions!

Here is my code:

#!/bin/bash
dbpasswd=$(cat /etc/passwd | cut -d ":" -f3 | sort -n)
hpass=$(printf '%d\n' "$dbpasswd")  #to put all numbers on separeate line
while true; do
read -p "Enter a number between 1000 and 59999" num
echo ""
if [[ "$num" -gt 1000 && "$num" -lt 60000 ]]; then
   if [[ "$num" -eq "$hpass" ]]; then 
   echo "$num is already in use"
   else
   echo "$num is in range and not yet used!"
   break
   fi
else
   echo "$num is out of range"
fi
done
1

There are 1 best solutions below

0
markp-fuso On

Load the list of /etc/passwd uids into an array:

uids=()

while read -r uid
do
    uids[$uid]="$uid"
done < <(cut -d":" -f3 /etc/passwd)

Modifying OP's current code to test if $num is an element in the array:

while true; do
    read -p "Enter a number between 1000 and 59999: " num
    echo ""

    if [[ "$num" -gt 1000 && "$num" -lt 60000 ]]; then
        if [[ -n "${uids[num]}" ]]; then 
            echo "$num is already in use"
        else
            echo "$num is in range and not yet used!"
            break
        fi
    else
        echo "$num is out of range"
    fi
done