0

我一直在尝试学习 bash 中逻辑语句的语法,如何执行 if/else,管道等。我正在尝试构建一个 bash 脚本,但是在 3 个小时没有了解这些东西的工作原理之后,我惨遭失败。

现在我需要这个小脚本,我会尝试用一个通用代码来解释它,或者随便你怎么称呼它。干得好:

while variable THRESHOLD = 10

{
if netstat -anltp contains a line with port 25565
then set variable THRESHOLD to 0 and variable PROCNUM to the process number,
else add 1 to variable THRESHOLD
sleep 5 seconds
}
kill the process No. PROCNUM
restart the script

基本上,它的作用是,一旦套接字关闭,经过几次尝试,它就会终止正在侦听该端口的进程。

我很确定这是可能的,但我不知道如何正确地做到这一点。主要是因为我不懂管道,也不是很熟悉 grep。提前谢谢你的帮助。

4

2 回答 2

1
    #!/bin/bash
    # write a little function
    function do_error {
        echo "$@" 1>&2
        exit 1
    }
    # make the user pass in the path to the executable
    if [ "$1" == "" ]; then
        do_error "USAGE: `basename $0` <path to your executable>"
    fi
    if [ ! -e $1 ]; then
        do_error "Unable to find executable at $1"
    fi
    if [ ! -x $1 ]; then
        do_error "$1 is not an executable"
    fi
    PROC="$1"
    PROCNAME=`basename $PROC`

    # forever
    while [ 1 ]; do
        # check whether the process is up
        proc=`ps -ef | grep $PROCNAME 2>/dev/null`
        # if it is not up, start it in the background (unless it's a daemon)
        if [ "$proc" == "" ]; then
            $PROC &
        fi
        # reinitialize the threshold
        threshold=0
        # as long as we haven't tried 10 time, continue trying
        while [ threshold -lt 10 ]; do
            # run netstat, look for port 25565, and see if the connection is established. 
            # it would be better to checks to make sure
            # that the process we expect is the one that established the connection
            output=`netstat -anp | grep 25565 | grep ESTABLISHED 2>/dev/null`
            # if netstat found something, then our process was able to establish the connection
            if [ "$output" != "" ]; then
                threshold = 0
            else
                # increment the threshold
                threshold=$((threshold + 1))
            fi
            # i would sleep for one second
            sleep 1
        done
        kill -9 $PROCNUM
    done
于 2013-06-24T18:59:01.977 回答
1

不想冒犯,但如果你可以编写一个“通用”程序,你所需要的就是学习, for bash的语法并阅读等等的手册页......whileifgrepkill

pipes你花园里的一样。有两件事:tappond。您可以通过多种方式(例如下雨)填充您的池塘。此外,您可以打开水龙头取水。但如果你想用水龙头里的水填满池塘,就需要一根管子。就这样。句法:

tap | pond
  • 水龙头的输出
  • 用管子连接
  • 到池塘的(输入)

例如

netstat | grep
  • 的输出netstat
  • 用管子连接
  • 到的输入grep

这就是魔法...... :)

关于语法:您将问题标记为bash.

因此,在谷歌上搜索bash while syntax将显示给你,这个初学者 Bash 指南

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_02.html

到,你可以if在同一个网站上阅读。

简直不敢相信,在 3 小时后,您无法理解使用 bash 语法编写程序的基本whileif语法——尤其是当您能够编写“通用”程序时……

写起来并不难(修改上面页面中的第一个示例):

THRESHOLD="0"
while [ $THRESHOLD -lt 10 ]
do
    #do the IF here
    THRESHOLD=$[$THRESHOLD+1]
done

等等...

于 2013-06-24T19:51:54.147 回答