当 shell 脚本使用 bash -c 调用自身时,包括 $@ 以传递所有命令行参数

Including $@ to pass on all command line arguments when a shell script invokes itself with bash -c

我需要一个 bash 脚本来调用自身(实际上在不同的上下文中,在 Docker 容器内)并且我正在使用 bash -c 命令来执行此操作。但是,即使在此处阅读了很多相关问题之后,我仍在为如何传递所有命令行变量而苦苦挣扎。这是一个示例脚本:

#!/bin/bash
# If not in the right context, invoke script in right context and exit
if [ -z ${NESTED+x} ]; then
  NESTED=true bash -c "./test.sh $@"
  exit
fi

echo ""
echo ""
echo ""

如果我将其保存为 test.sh 并使用 ./test.sh 1 2 "3 4" 调用它,我希望看到这些参数被回显,但只有第一个被输出。

如果我使用 set -x,它显示 bash 插入了一些意外的引号,因此调用变为 NESTED=true bash -c './test2.sh 1' 2 3 4。这解释了输出,但我一直无法找出正确的方法。

不应使用

bash -c,因为它无法轻松处理 "3 4"

#!/bin/bash
# If not in the right context, invoke script in right context and exit
if [ -z ${NESTED+x} ]; then
  NESTED=true ./test.sh "$@"
  exit
fi

echo ""
echo ""
echo ""