通过转义必要的东西将shell脚本转换为一行?

2024-04-23 12:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过转义所有内容将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将上述脚本转换成一行代码?你知道吗


Tags: 代码echo脚本内容dataifserveris
1条回答
网友
1楼 · 发布于 2024-04-23 12:26:47

你为什么要那样?每个换行符都可以用分号替换,基本上就是这样。在dothenelse之后,不要加分号(感谢@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; ...

相关问题 更多 >