Short for loop for fetching bash users

Issue

A short python script i wrote to fetch users who are using bash. below is script. I don’t know why its not working. Please share your ideas as to how this program is working inside.I am beginner in python and looking for lectures on data structures and algorithms. any answers are welcome. Thanks

f = open("/etc/passwd")

mainshell = '/bin/bash'
for line in f:
    field = line.split(:)
    shell = field[-1]
    user  = field[0]
    if shell = mainshell:
        print(user)

edit: I am getting no output. I tried to fetch values of variable shell and users and that exactly what i need but somehow if block is not working. Its not giving any error but just not working.

Solution

You are almost there with your script. But there are 2 reasons why its not working.

  1. Your if statement is not doing a string comparison. You should be using == not =
  2. You compare the string mainshell with shell, but you assume shell does not contain whitespaces. But the string will probably look like this /bin/bash (notice the whitespaces at the end?). This can be removed with shell = field[-1].strip()

I think then your program should work fine 🙂

Answered By – Haller Patrick

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published