Home > Net >  Operand expected (error token is "/ur/sbin/no login >= 1000 ")
Operand expected (error token is "/ur/sbin/no login >= 1000 ")

Time:06-07

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 ")

CodePudding user response:

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}'.

  • Related