Shell 通过SSH运行源scriptname时退出脚本

Shell 通过SSH运行源scriptname时退出脚本,shell,scripting,ssh,exit,Shell,Scripting,Ssh,Exit,我有一个包含许多选项的脚本,其中一个选项集应该更改目录,然后退出脚本,但是通过ssh运行源代码以使其在父级中更改它退出ssh是否有其他方法来执行此操作以使其不退出?我的脚本位于/usr/sbin目录中。您可以尝试让脚本运行子shell,而不是使用任何方法“更改父目录中的[目录]”(假设您让子脚本打印出cd命令,让父脚本执行类似eval“$(脚本--打印cd)”)。因此,请添加一个启动$SHELL新实例的--subshell选项,而不是(例如)一个--print cd选项 d=/path/to/s

我有一个包含许多选项的脚本,其中一个选项集应该更改目录,然后退出脚本,但是通过ssh运行源代码以使其在父级中更改它退出ssh是否有其他方法来执行此操作以使其不退出?我的脚本位于/usr/sbin目录中。

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

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