从bash文件中读取数组-“未找到”使用猫的错误 [英] Reading an array from a file in bash - "not found" errors using cat
问题描述
我有一个带有一些基本单词的文本文件:
I have a text file with a few basic words:
-banana
-mango
-sleep
当我运行脚本时:
#!/bin/sh
WORD_FILE="testwoord.txt"
WORDS_ARRAY=cat $WORD_FILE
输出如下:
/home/username/bin/testword.txt: 1 /home/username/bin/restword.txt: banana: not found
/home/username/bin/testword.txt: 1 /home/username/bin/restword.txt: mango: not found
/home/username/bin/testword.txt: 1 /home/username/bin/restword.txt: sleep: not found
为什么要这样做?我真正想要的是一个脚本,可以从.txt文件中读取单词并将其放入数组中。
Why is it doing this? What I actually want is a script that reads words from a .txt file and puts it in an array.
推荐答案
要解释为什么不起作用:
WORDS_ARRAY=cat $WORD_FILE
运行通过扩展,字符串拆分和glob扩展 $ WORD_FILE
在环境中导出的变量 WORDS_ARRAY
的值为
runs the command generated by expanding, string-splitting, and glob-expanding $WORD_FILE
with the variable WORDS_ARRAY
exported in the environment with the value cat
.
相反,请考虑:
#!/bin/bash
# ^^ -- important that this is bash, not sh: POSIX sh doesn't have arrays!
WORD_FILE=testword.txt
readarray -t WORDS_ARRAY <"$WORD_FILE"
printf 'Read a word: %q\n' "${WORDS_ARRAY[@]}"
...这将创建一个 actual 数组,而不是包含空格的字符串变量(如 WORDS_ARRAY = $(cat $ WORD_FILE)
一样)。
...which will create an actual array, not a string variable containing whitespace (as WORDS_ARRAY=$(cat $WORD_FILE)
would).
顺便说一句,在这里使用大写的变量名是不好的形式。引用POSIX规范:
By the way, using all-upper-case variable names is bad form here. To quote the POSIX spec:
POSIX.1-2008的Shell and Utilities卷中的实用程序使用的环境变量名称仅包含以下内容:大写字母,数字和可移植字符集中定义的字符中的('_'),并且不能以数字开头。实现可能允许其他字符;申请应容忍此类名称的存在。大写和小写字母应保留其唯一标识,并且不能折叠在一起。 包含小写字母的环境变量名称的名称空间保留给应用程序。应用程序可以使用此名称空间中的名称定义任何环境变量,而无需修改标准实用程序的行为。
这篇关于从bash文件中读取数组-“未找到”使用猫的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!