I have a text file with a few basic words:
-banana
-mango
-sleep
When I run my script:
#!/bin/sh
WORD_FILE="testwoord.txt"
WORDS_ARRAY=cat $WORD_FILE
The output is like:
/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
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.
To explain why this doesn't work:
runs the command generated by expanding, string-splitting, and glob-expanding
$WORD_FILE
with the variableWORDS_ARRAY
exported in the environment with the valuecat
.Instead, consider:
...which will create an actual array, not a string variable containing whitespace (as
WORDS_ARRAY=$(cat $WORD_FILE)
would).By the way, using all-upper-case variable names is bad form here. To quote the POSIX spec:
To complement Charles Duffy's helpful answer:
Note that the variable names were changed to lowercase, as per Charles' recommendation.
Here a bash 3.x (and above) version of the command for reading lines into a bash array (
readarray
requires bash 4.x):If you want to store individual words (across lines), use:
To print the resulting array: