【问题标题】:I am puzzled with the differences between "sh xxx.sh" and "./xxx.sh" for running a shell script我对运行 shell 脚本的“sh xxx.sh”和“./xxx.sh”之间的区别感到困惑
【发布时间】:2015-07-17 10:04:40
【问题描述】:

在这里,我有一个名为 load.sh 的 shell 脚本。

它启动我的名为“demo”的程序并进行监督, 当我用sh load.sh start | stop 运行它时,它运行良好。

但是,当我使用 ./load.sh start | stop 运行它时,它的效果很差。演示经常由监督启动(和退出)。

这两种运行shell脚本的方式有什么问题? 脚本中是否有任何问题(错误)导致监督频繁重启演示? 非常感谢!

#!/bin/bash

cd `dirname $0` || exit
mkdir -p status/demo

dir_name=`pwd`
STR_LIB=${dir_name}/lib

if [ -z "${LD_LIBRARY_PATH}" ]; then
    export LD_LIBRARY_PATH="${STR_LIB}"
else
    export LD_LIBRARY_PATH="${STR_LIB}:${LD_LIBRARY_PATH}"
fi

start() {
            sleep 1
            bin/supervise.demo -u status/demo bin/demo >/dev/null 2>&1 &
}

stop() {
            if [ -f status/demo/lock ]; then
                supervise_demo_pid=`/sbin/fuser status/demo/lock`
                `ps -ef | grep "$supervise_demo_pid" | grep "supervise.demo" | grep -v grep > /dev/null 2>&1`
                if [ $? -eq 0 ] && [ "$supervise_demo_pid" != "" ] ; then
                    echo "kill supervise.demo process:"${supervise_demo_pid}
                    kill -9 $supervise_demo_pid
                fi
            fi

            if [ -f status/demo/status ]; then
                demo_pid=`od -An -j16 -N2 -tu2 status/demo/status`
                `ps -ef | grep "$demo_pid" | grep "demo" | grep -v grep > /dev/null 2>&1`
                if [ $? -eq 0 ]; then
                    echo "kill demo process:"${demo_pid}
                    kill -9 $demo_pid
                fi
            fi
}

case "$1" in
        start)
            stop
            start
            echo "Done!"
            ;;
        stop)
            stop
            echo "Done!"
            ;;
           *)
           echo "Usage: $0 {start|stop}"
           ;;
esac

【问题讨论】:

    标签: linux bash shell sh


    【解决方案1】:

    sh script.shsh 中运行脚本,而以./script.sh 运行它时使用在其第一行“shebang”中指定的任何内容——在本例中为/bin/bash

    sh/bin/bash 可能是不同的 shell,因此它们对脚本的解释不同。 sh 是什么取决于您的发行版、$PATH、别名等。

    【讨论】:

      【解决方案2】:

      当您通过./load.sh start | stop 运行脚本时,它使用shebang 中指定的处理器运行。在您的情况下,它是 bash:

      #!/bin/bash
      

      sh load.sh start | stop 呢。在 Ubuntu 中(默认)sh 实际上只是一个链接并且指向dash。 要检查它:

      $ which sh
      /bin/sh
      $ ls -l /bin/sh
      lrwxrwxrwx 1 root root 4 Mar 16 00:54 /bin/sh -> dash
      

      【讨论】:

      • 此外,sh 可能不是/bin/sh
      【解决方案3】:

      sh foo 将在 $path 中搜索可执行的 foo sh ./foo 要求从 $cwd 执行

      两者 foo 和 ./foo 通过这里提到的 shebang 运行

      所有表单都将调用 foo 并使用引用的特定文件的权限,包括 suid、guid

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        • 2013-02-06
        • 2014-08-30
        • 2015-01-06
        • 2020-07-31
        相关资源
        最近更新 更多