简体   繁体   中英

Complex Bash loop structure in Python3 script

I want to run a (complex) Bash while loop from a Python3 script. I know os.subprocess and os.subprocess.check_output works in this case, but I can't wrap my head around how to include the while inside a Python subprocess.

while read -r line
do
    if [ "$(echo "$line" | cut -d : -f 7)" = "/bin/bash" ] && [ $(printf "$(echo "$line" | cut -d : -f 1)" | wc -c) -gt $mida ]
    then
        echo $line | cut -d : -f 1
    fi
done < /etc/passwd

I've tried the following:

out=subprocess.check_output(""" while read -r line; do; if [ "$(echo "$line" | cut -d : -f 7)" = "/bin/bash" ] && [ $(printf "$(echo "$line" | cut -d : -f 1)" | wc -c) -gt $mida ]; then; echo $line | cut -d : -f 1; fi; done < /etc/passwd """, shell=True)

Just include it normally. Like it is. You are using """ quotes anyway.

out = subprocess.check_output("""
while read -r line
do
    if [ "$(echo "$line" | cut -d : -f 7)" = "/bin/bash" ] && [ $(printf "$(echo "$line" | cut -d : -f 1)" | wc -c) -gt $mida ]
    then
        echo $line | cut -d : -f 1
    fi
done < /etc/passwd
""", shell=True)

Notes:

  • you should export mida environment variable before using it. When $mida variable is not set will result in some [: something expected but not there messages.
  • printf "$(stuff)" | wc -c printf "$(stuff)" | wc -c ? Just stuff | wc -c stuff | wc -c .
  • Check your scripts with http://shellcheck.net
  • Read https://mywiki.wooledge.org/BashFAQ/001
  • Just split the line on : using IFS when reading instead of using cut
  • And that said, do not use shell - use python and write the logic in python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM