I have a very simple script that reads in the contents of a file (_open.txt) into an array "lyrics":
#!/bin/sh
# read in the text
lyrics=( `cat _open.txt` | tr '\n' ' ')
exit 0
It gives the following error message:
./lyrics.sh: 1: Syntax error: word unexpected (expecting ")")
I have also tried
lyrics=($(cat _open.txt))
as well as with and without quotes (single and double) around the filename.
but it yields the same error message. The path /bin/sh is correct. What is the error message really saying?
#bash:
declare -a lyrics=$( < _open.txt )
#ksh
set -A lyrics=$( < _open.txt )
If you are using bash or ksh this will work. ksh limits the number of elements in an array to 1023. So _open.txt has to have less than 1024 "words" in it.
Thank you for your prompt response. What is the cause of the syntax error? By the way, the file contains a large word, ie a body of text without spaces, so is there a limit to what the array lyrics can hold in terms of maximum size of array element?
Neither declaration is necessary. In either bash or ksh93, simply assigning it is enough:
lyrics=( $( tr '\n' ' ' < _open.txt ) )
Note that you do not need tr; the shell will split the array on the characters in $IFS, which normally includes a space. So this is the same as the above:
lyrics=( $( < _open.txt ) )
Ksh88 was limited to 1023 elements, but I don't think it accepted that syntax for assigning a number of elements to an array.
Ksh used to be limited to 4096 elements in an array, but versions for the last few years have, like bash, been limited only by available memory.
I disagree. Simply because you can NOT do something and have it work doesn't necessarily mean it is a great idea. There is a concept: self-documenting code.
Yes, syntactically, you are correct. In terms of good practice you are not. IMO.
You obviously do not buy this idea, so it's okay. Perderabo & I have gone around on this as well.
My point: In real world shops, especially now, people come & go & get outsourced.
Harder to read code is harder to maintain. Period. See 'Code Complete' by Steve McConnell 2nd Ed. Small changes to improve readability matter in the long run because 95% of the cost of software is in maintenance....
Unless this is a massive system operation running in an environment where you need to limit process resource usage as much as possible, code obfuscation in an attempt to gain performance is not de facto a good idea always. Not that this example makes much difference performance wise. Just coding for the 'next guy'.