I am trying to split the string by ':' and store it in an array, so something that looks like a:b:c:d:x:y:z will be stored in an array which holds, a, b, c, d, x, y, z as elements.
What I have written is
IFS = ':' read - r -a ARR <<< "$INFO"
where INFO is a string which is being read in from a file containing multiple strings in the aforementioned format.
I get an error saying "IFS: command not found".
I am reading them in this way:
while read INFO
Lastly when I try to assign the first element in the array to a variable, I am getting an error:
export NAME = $INFO[0]
the two errors I get here are export: '=' not a valid identifier and export: '[0]: not a valid identifier
I am relatively a newcomer to bash.
The basic problem here is that your code contains spaces in places where they aren't allowed. For instance, the following is perfectly fine syntax (though it fails to comply with POSIX conventions on variable naming, which advises lowercase characters be used for application-defined names):
info_string='a:b:c:d:x:y:z'
IFS=: read -r -a info_array <<< "$info_string"
Similarly, on a dereference, you need curly braces, and (again) can't put spaces around the =:
name=${info_array[0]}
This works:
s=a:b:c:d #sample string
IFS=:
a=( $s ) #array
printf "'%s' " "${a[@]}" #prints 'a' 'b' 'c' 'd'
The syntax to get the n-th item in an array is
${array_name[$index]}
(The curlies are required), so you need export NAME="${INFO[0]}" (assignments normally don't need to be quoted, however with export, declare, local, and similar, it's better to quote).
https://www.lukeshu.com/blog/bash-arrays.html is a good tutorial on how bash arrays work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With