从其他文件读取 Bash 变量赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20406134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:54:03  来源:igfitidea点击:

Read a Bash variable assignment from other file

bashshellunixscripting

提问by Marcos Griselli

I have this test script:

我有这个测试脚本:

#!/bin/bash
echo "Read a variable" 
#open file
exec 6<test.txt
read EXAMPLE <&6
#close file again
exec 6<&-
echo $EXAMPLE

The file test.txthas only one line:

该文件test.txt只有一行:

EXAMPLE=1

The output is:

输出是:

bash-3.2$ ./Read_Variables.sh
Read the variable
EXAMPLE=1

I need just to use the value of $EXAMPLE, in this case 1. So how can I avoid getting the EXAMPLE=part in the output?

$EXAMPLE在这种情况下,我只需要使用 的值1。那么我怎样才能避免EXAMPLE=在输出中得到这个部分呢?

Thanks

谢谢

回答by Joe Holloway

If the file containing your variables is using bash syntax throughout (e.g. X=Y), another option is to use source:

如果包含变量的文件始终使用 bash 语法(例如 X=Y),另一种选择是使用source

#!/bin/bash
echo "Read a variable" 
source test.txt
echo $EXAMPLE

回答by chepner

As an alternative to sourcing the entire file, you can try the following:

作为获取整个文件的替代方法,您可以尝试以下操作:

while read line; do
    [[ $line =~ EXAMPLE= ]] && declare "$line" && break
done < test.txt

which will scan the file until it finds the first line that looks like an assignment to EXAMPLE, then use the declarebuiltin to perform the assignment. It's probably a little slower, but it's more selective about what is actually executed.

它将扫描文件,直到找到看起来像对 的赋值的第一行EXAMPLE,然后使用declare内置函数来执行赋值。它可能会慢一点,但它对实际执行的内容更具选择性。

回答by Micha? Trybus

I think the most proper way to do this is by sourcing the file which contains the variable (if it has bash syntax), but if I were to do that, I'd source it in a subshell, so that if there are ever other variables declared there, they won't override any important variables in current shell:

我认为最正确的方法是获取包含变量的文件(如果它具有 bash 语法),但如果我要这样做,我会在子外壳中获取它,以便如果有其​​他在那里声明的变量,它们不会覆盖当前 shell 中的任何重要变量:

(. test.txt && echo $EXAMPLE)

回答by Marcos Griselli

You could read the line in as an array (notice the -aoption) which can then be indexed into:

您可以将该行作为数组读取(注意-a选项),然后可以将其编入索引:

# ...
IFS='=' read -a EXAMPLE <&6
echo ${EXAMPLE[0]} # EXAMPLE
echo ${EXAMPLE[1]} # 1
# ...

This call to readsplits the input line on the IFSand puts the remaining parts into an indexed array. See help readfor more information about readoptions and behaviour. You could also manipulate the EXAMPLEvariable directly:

此调用read拆分 上的输入行IFS并将其余部分放入索引数组中。help read有关read选项和行为的更多信息,请参见。您也可以EXAMPLE直接操作变量:

# ...
read EXAMPLE <&6
echo ${EXAMPLE##*=} # 1
# ...

If all you need is to "import" other Bash declarations from a file you should just use:

如果您只需要从文件中“导入”其他 Bash 声明,您应该使用:

source file