如何从文件中读取变量?
我想在我的脚本中插入一个我将从文本文件中读取的值(字符串)。
例如,而不是:
echo "Enter your name" read name
我想从另一个文本文件中读取一个字符串,因此解释器应该从文件中读取字符串而不是用户输入。
要从文件中读取变量,我们可以使用source
或.
命令。
让我们假设该文件包含以下行
MYVARIABLE="Any string"
然后我们可以使用导入此变量
#!/bin/bash source echo $MYVARIABLE
考虑到您希望将文本文件的所有内容保存在变量中,您可以使用:
#!/bin/bash file="/path/to/filename" #the file where you keep your string name name=$(cat "$file") #the output of 'cat $file' is assigned to the $name variable echo $name #test
或者,在纯粹的bash中:
#!/bin/bash file="/path/to/filename" #the file where you keep your string name read -d $'\x04' name < "$file" #the content of $file is redirected to stdin from where it is read out into the $name variable echo $name #test
在脚本中,您可以执行以下操作:
read name < file_containing _the_answer
你甚至可以多次这样做,例如循环
while read LINE; do echo "$LINE"; done < file_containing_multiple_lines
另一种方法是将标准输入重定向到您的文件,您可以按照程序预期的顺序输入所有用户。 例如,使用该程序(称为script.sh
)
#!/bin/bash echo "Enter your name:" read name echo "...and now your age:" read age # example of how to use the values now stored in variables $name and $age echo "Hello $name. You're $age years old, right?"
和输入文件(称为input.in
)
Tomas 26
您可以通过以下两种方式之一从终端运行此命令:
$ cat input.in | ./script.sh $ ./script.sh < input.in
它等同于只运行脚本并手动输入数据 - 它会打印出“Hello Tomas。你26岁了,对吗?”。
正如RaduRădeanu 已经建议的那样 ,您可以在脚本中使用cat
将文件的内容读取为可变文件 - 在这种情况下,您需要每个文件只包含一行,只需要该特定变量所需的值。 在上面的示例中,您将输入文件拆分为具有名称(例如, name.in
)的文件和具有年龄的文件(例如, age.in
),并将read name
和read age
行更改为name=$(cat name.in)
和age=$(cat age.in)
。
简短回答:
name=`cat "$file"`
我在这里找到了有效的解决方案: https : //af-design.com/2009/07/07/loading-data-into-bash-variables/
if [ -f $SETTINGS_FILE ];then . $SETTINGS_FILE fi
如果你想使用多个字符串,你可以使用:
path="/foo/bar"; for p in `cat "$path"`; do echo "$p" ....... (here you would pipe it where you need it)
要么
如果您希望用户指明该文件
read -e "Specify path to variable(s): " path; for p in 'cat "$path"'; do echo "$p" ............................
name=$(<"$file")
从man bash:1785
,这个命令替换相当于name=$(cat "$file")
但更快。