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:
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
. :
using IFS
when reading instead of using cut
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.