【问题标题】:exiting script while running source scriptname over SSH通过 SSH 运行源脚本名时退出脚本
【发布时间】:2011-02-09 23:12:23
【问题描述】:

我有一个脚本,其中包含许多选项,其中一个选项集应该更改目录,然后退出脚本,但是在 ssh 上运行源代码以使其在退出的父级中更改 SSH 在那里另一种方法来做到这一点,使其不退出?我的脚本在 /usr/sbin 目录中。

【问题讨论】:

    标签: shell scripting ssh exit


    【解决方案1】:

    您可以尝试让脚本运行一个子shell,而不是它使用的任何方法来“更改父级中的[目录]”(假设您让子级打印出cd 命令并让父级执行类似的操作eval "$(script --print-cd)")。因此,不要(例如)--print-cd 选项,而是添加一个 --subshell 选项来启动 $SHELL 的新实例。

    d=/path/to/some/dir
    #...
    cd "$d"
    #...
    if test -n "$opt_print_cd"; then
        sq_d="$(printf %s "$d" | sed -e "s/'/'\\\\''/g")"
        printf "cd '%s'\n" "$sq_d"
    elif test -n "$opt_subshell"; then
        exec "$SHELL"
    fi
    

    如果您不能编辑脚本本身,您可以制作一个包装器(假设您有权在“服务器”上创建新的持久文件):

    #!/bin/sh
    script='/path/to/script'
    print_cd=
    for a; do test "$a" = --print-cd && print_cd=yes && break; done
    if test -n "$print_cd"; then 
        eval "$("$script" ${1+"$@"})" # use cd instead of eval if the script prints a bare dir path
        exec "$SHELL"
    else
        exec $script" ${1+"$@"}
    fi
    

    【讨论】:

      最近更新 更多