Ale*_*lls 5 bash shell-script environment-variables arguments variable
我有一个参数列表和三个过程:
bash_script -> child -> grandchild
Run Code Online (Sandbox Code Playgroud)
参数列表是针对孙子的。我可以修改所有三个进程。祖父脚本为自己获得了一个参数。
以下是将剩余参数传递给孙子的正确方法吗?
#!/usr/bin/env bash
# This is the grandfather
first_arg="$1"
shift 1;
export MY_ARGS="$@"
Run Code Online (Sandbox Code Playgroud)
我稍后在子进程中“传播”了 env 变量,作为调用孙子进程的命令的一部分,例如:
grandchild --foo "$MY_ARGS" # append $MY_ARGS as arguments to foo
Run Code Online (Sandbox Code Playgroud)
在脚本中,不应将数组降级为字符串。环境变量及其值是一个简单的key=value对,其中key和value都是字符串。将位置参数降级为一个简单的字符串(通过串联)将很难保持它们之间的分离,并且当您最终想要使用它们时很难正确引用。
相反,将要传递给其命令行上的下一个脚本的位置参数(命令行参数)传递。
#!/bin/bash
first_arg=$1
shift
# later ...
./my_other_script "$@"
Run Code Online (Sandbox Code Playgroud)
在另一个脚本中:
#!/bin/bash
# use "$@" here
foo --bar "$@"
Run Code Online (Sandbox Code Playgroud)