如何通过转义一切来转换单行中的shell脚本?例如:用\ n替换行尾,并加倍其他反斜杠和其他必要的东西。
#!/bin/bash
HOSTNAME=$hostname
DATA=""
RETRY=50
echo $HOSTNAME
sleep 1m
while true; do
while [ $RETRY -gt 0 ]
do
DATA=$(wget -O - -q -t 1 http://$HOSTNAME:8080/process)
if [ $? -eq 0 ]
then
break
else
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null ;
then
echo "Server is already running"
else
echo "Server is not running so starting it"
/opt/abc/hello start
fi
let RETRY-=1
sleep 30
fi
done
if [ $RETRY -eq 0 ]
then
echo "Server is still down. Exiting out of shell script." >&2
exit 2
fi
echo "Server is up. Now parsing the process."
#grep $DATA for state
state=$(grep -oP 'state: \K\S+' <<< "$DATA")
[[ -z "$state" ]] && state=0
echo "$state"
#validate the conditions
if [[ "$state" == "DONE" || "$state" == "0" ]]; then exit 0; fi
#wait another 30 seconds
sleep 30
done
有没有办法通过逃避所有必要的事情,使用Python或Linux转换上述脚本?
答案 0 :(得分:1)
你为什么要这样?每个换行符都可以用分号替换,基本上就是这样。在do
,then
和else
之后,不要添加分号(感谢@Cyrus指出这一点!)您还需要删除评论。
hostname
但从未声明过。 http://shellcheck.net/给出了5个警告,但大多数都是相当温和的。 if [ $? -eq 0 ]
反模式是我的一个宠儿,我非常希望看到修复。
此外,缩进也被打破了,但是当然如果你真的认为你需要这个是单行则无关紧要。
如果(如在your deleted question中)想要将其嵌入到Python脚本中,则无需用其他任何内容替换换行符。 Python可以简单地通过'''triple-quoting it'''
接受包含换行符的字符串(尽管您希望r'''raw string'''
避免让Python解释并替换反斜杠。)
script=r'''#!/bin/bash
DATA=""
RETRY=50
# avoid copying the variable; quote the string
echo "$hostname"
sleep 1m
while true; do
# fix indentation
while [ $RETRY -gt 0 ]
do
# avoid useless use of if [ $? -eq 0 ]
# quote URL for mainly stylistic reasons
if DATA=$(wget -O - -q -t 1 "http://$hostname:8080/process")
then
break
else
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null ;
then
# Consistently use stderr for diagnostic messages
echo "Server is already running" >&2
else
echo "Server is not running so starting it" >&2
/opt/abc/hello start
fi
let RETRY-=1
sleep 30
fi
done
if [ $RETRY -eq 0 ]
then
echo "Server is still down. Exiting out of shell script." >&2
exit 2
fi
# stderr again
echo "Server is up. Now parsing the process." >&2
state=$(grep -oP 'state: \K\S+' <<< "$DATA")
# use a default
state=${state:-0}
echo "$state"
if [[ "$state" == "DONE" || "$state" == "0" ]]; then exit 0; fi
sleep 30
done'''
这里有分号。简明扼要,因为我确信你明白了。
DATA=""; RETRY=50; echo "$hostname"; sleep 1m; while true; do \
while [ $RETRY -gt 0 ]; do if DATA=$(wget -O - -q -t 1 "http://$hostname:8080/process"); then break; ...