bash 在子命令中重定向
bash redirect in subcommand
我对 bash 重定向尝试感到困惑。我正在尝试 运行 一个将重定向作为 screen
的子命令的命令,重定向转到子命令而不是 screen
.
这是原始命令的清理版本:
ssh -o "StrictHostKeyChecking no" <user>@<host> 'bash -s' < my_script.sh -- -s OPTION1 -o OPTION2
这完全符合预期。但是,我尝试 运行 在 screen
下将其设置为中断:
screen -d -m ssh -o "StrictHostKeyChecking no" <user>@<host> 'bash -s' < my_script.sh -- -s OPTION1 -o OPTION2
我可以看到现在重定向到 screen
而不是 ssh
,但我不知道如何让它按照我想要的方式工作。
如果您有一些工作代码,请将其导出为一个函数,然后从 screen
启动的子 shell 中调用该函数。这样一来,您的代码将 运行 与 不涉及 屏幕的情况完全一样。
#!/usr/bin/env bash
# ^^^^- IMPORTANT: 'export -f' requires the parent and child shells to both
# persist functions in the environment in the same way. If the child is
# bash, the parent must be bash too!
option1=
option2=
runCommand() {
[[ $user && $host ]] || { echo "ERROR: user and host not exported" >&2; return 1; }
option1=; option2=
printf -v cmd_str '%q ' -s "$option1" -o "$option2"
ssh -o "StrictHostKeyChecking no" "${user}@${host}" \
"bash -s -- $cmd_str" <my_script.sh
}
export -f runCommand
screen -d -m bash -c 'runCommand "$@"' _ "$option1" "$option2"
如果您的代码使用了您没有向我们展示的变量,请确保也 export
它们,以便导出的函数可以访问它们。
我对 bash 重定向尝试感到困惑。我正在尝试 运行 一个将重定向作为 screen
的子命令的命令,重定向转到子命令而不是 screen
.
这是原始命令的清理版本:
ssh -o "StrictHostKeyChecking no" <user>@<host> 'bash -s' < my_script.sh -- -s OPTION1 -o OPTION2
这完全符合预期。但是,我尝试 运行 在 screen
下将其设置为中断:
screen -d -m ssh -o "StrictHostKeyChecking no" <user>@<host> 'bash -s' < my_script.sh -- -s OPTION1 -o OPTION2
我可以看到现在重定向到 screen
而不是 ssh
,但我不知道如何让它按照我想要的方式工作。
如果您有一些工作代码,请将其导出为一个函数,然后从 screen
启动的子 shell 中调用该函数。这样一来,您的代码将 运行 与 不涉及 屏幕的情况完全一样。
#!/usr/bin/env bash
# ^^^^- IMPORTANT: 'export -f' requires the parent and child shells to both
# persist functions in the environment in the same way. If the child is
# bash, the parent must be bash too!
option1=
option2=
runCommand() {
[[ $user && $host ]] || { echo "ERROR: user and host not exported" >&2; return 1; }
option1=; option2=
printf -v cmd_str '%q ' -s "$option1" -o "$option2"
ssh -o "StrictHostKeyChecking no" "${user}@${host}" \
"bash -s -- $cmd_str" <my_script.sh
}
export -f runCommand
screen -d -m bash -c 'runCommand "$@"' _ "$option1" "$option2"
如果您的代码使用了您没有向我们展示的变量,请确保也 export
它们,以便导出的函数可以访问它们。