-1

This is my code:

#!/bin/bash

function userList() {
for line in $(cat /etc/passwd)
do
    USER=$(echo $line | cut -d":" -f1)
    USERID=$(echo $line | cut -d":" -f3)
    if (( $USERID >= 1000 ))
        then
                echo $USER
        fi
done
}

I want it to show all the users of the system but every time I call the function in the terminal it throws the names of the users but also this errors:

syntax error: operand expected (error token is "/ur/sbin/no login >= 1000 ")
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Does this answer your question? [How can I compare numbers in Bash?](https://stackoverflow.com/questions/18668556/how-can-i-compare-numbers-in-bash) – Martin Zeitler Jun 06 '22 at 18:30
  • @MartinZeitler What's the relevance? The OP is using `(( ))` correctly. – John Kugelman Jun 06 '22 at 18:31
  • Also `/ur/sbin/no login` appears to be invalid. Comparing string to number... which means `$USERID` is not being assigned properly. `awk -F':' '{ print $1}' /etc/passwd` is way simpler / easier. – Martin Zeitler Jun 06 '22 at 18:34

1 Answers1

1
for line in $(cat /etc/passwd)

That's not iterating over lines in the file, but over words in the file, where a word is separated by a space or tab or newline. When the line contains two words, then $line becomes something else, then echo $line | cut -d":" -f3 may not be a number. For example on this line:

name:password:UID:GID:A comment:directory:shell

Then $line will be equal to name:password:UID:GID:A on first loop iteration, than to comment:directory:shell on second loop iteration. On the second time, your script give an error - shell is not a number.

Check your script will shellcheck. Quote variable expansions. Use while IFS= read- r to read a file line by line, or in this case while IFS=: read -r to read field by field. Consider reading a tutorial on how to do basic shell scripting, like reading a file line by line. You may read about https://mywiki.wooledge.org/BashFAQ/001 . And, consider writing it in awk, it will be just awk -F: '$3>=1000{print $1}'.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111