jon*_*789 3 bash shell-script variable
我试图将变量从一个脚本导出到主脚本,并将导入的变量之一作为参数传递给主脚本。
这是fruitcolour.sh
只有变量的脚本:
apple="Red"
mango="Yellow"
orange="Orange"
pear="Green"
Run Code Online (Sandbox Code Playgroud)
这是主要脚本GetFruitColour.sh
:
#!/bin/bash
source fruitcolour.sh
echo "The colour of " $@ " is " $@ "."
Run Code Online (Sandbox Code Playgroud)
为了apple
作为参数传递,我想获取变量apple
ie的值Red
。
所以,当我跑 ./GetFruitColour.sh apple
它必须给出输出 :: The colour of apple is Red.
实现这一点的一种方法是通过间接——从第一个变量的值中引用另一个变量。
展示:
apple="Red"
var="apple"
echo "${!var}"
Run Code Online (Sandbox Code Playgroud)
结果是:
Red
Run Code Online (Sandbox Code Playgroud)
因为 bash 首先!var
表示var
变量的值,然后通过解释${apple}
并转换为Red
.
因此,您的 GetFruitColour.sh 脚本可能如下所示:
#!/bin/bash
source ./fruitcolour.sh
for arg in "$@"
do
printf 'The colour of %s is %s.\n' "$arg" "${!arg}"
done
Run Code Online (Sandbox Code Playgroud)
我已经将源脚本的路径设为相对路径而不是裸路径,以便更清楚地说明文件的位置(如果给定的文件名不包含斜杠,shell 将搜索$PATH
它的变量,这可能会让您感到惊讶)。
功能变化是使用循环变量$arg
和它的间接扩展来产生所需的值:
$ ./GetFruitColour.sh apple mango
The colour of apple is Red.
The colour of mango is Yellow.
Run Code Online (Sandbox Code Playgroud)
请注意,这里没有错误检查:
$ ./GetFruitColour.sh foo
The colour of foo is .
Run Code Online (Sandbox Code Playgroud)
您可能会发现使用关联数组更容易:
declare -A fruits='([orange]="Orange" [apple]="Red" [mango]="Yellow" [pear]="Green" )'
for arg in "$@"
do
if [ "${fruits["$arg"]-unset}" = "unset" ]
then
echo "I do not know the color of $arg"
else
printf 'The colour of %s is %s.\n' "$arg" "${fruits["$arg"]}"
fi
done
Run Code Online (Sandbox Code Playgroud)