bash在子命令中重定向

问题描述

我为尝试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=$1
option2=$2

runCommand() {
  [[ $user && $host ]] || { echo "ERROR: user and host not exported" >&2; return 1; }
  option1=$1; option2=$2
  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使用它们,以便导出的函数可以访问它们。