# Capture variables in Bash



## fullauto (Jan 7, 2013)

I am looking to capture input into variables that I can assign to an array.  However, I must be able to capture a string with spaces. I imagine that can't be too hard, but it has illuded me thus far.  

EG: 

```
#!/usr/local/bin bash

LINES=9
declare -a LINE=($1 $2 $3 $4 $5 $6 $7 $8 $9)


for (( c=0; c<$LINES; c++ ))
do

        echo "{LINE[$c]} = "${LINE[$c]}
done
```

However, that just captures the first nine words.  

```
./box this is the first variable::This is the second
```
should yield 
LINE[1]=this is the first variable
LINE[2]=This is the second

I am really stuck here. Any help would be greatly appreciated.


----------



## SirDice (Jan 7, 2013)

This might help: Bourne Shell Tutorial: $@ - All positional parameters with spaces.


----------



## fullauto (Jan 7, 2013)

Thanks. However, I already got that far.  What I'm really struggling with now is how to have the scripts read the whole line into an array with ++ as a delimiter. I know I could hack it together if there was some shell command or internal bash command to report back the position of a certain character in a string. I would they cature the positions into variables and simply use them to cut the string out to the delimiter.

any ideas?


----------



## SirDice (Jan 7, 2013)

I'd probably try to use read(1) and IFS. Another option is to resort to awk(1).


----------



## fullauto (Jan 7, 2013)

I have tried every instance of

```
read -a LINES
```
and such that my newbie scripting mind could conjour or copy and paste. No joy.


----------



## SirDice (Jan 7, 2013)

I don't think a double :: is allowed with IFS but a single : sure is:

```
#!/bin/sh

IFS=':'

echo "Some text:Another one with spaces:And another" | while read part
 do
        printf "%s\n" $part
 done
```


```
dice@vps-2417-1:~/test> ./test.sh
Some text
Another one with spaces
And another
```


----------



## fullauto (Jan 7, 2013)

But how do I get that to while loop through and add the fields to an array? That's the part that is driving me mad x(


----------



## fullauto (Jan 7, 2013)

WAIT !

I may have something.


```
STRING="$@"
echo "STRING = $STRING"

c=1
while [ $c -le 10 ]
do
        LINE[$c]=`echo $STRING | cut -d ":" -f $c`
        echo "\${LINE[$c]} is set to ${LINE[$c]}"
        c=$((c + 1))
done


exit 0
```

Produces


```
[ROOT@kif]/root/bin-> ./box tth:yyh:hh g: kiiu:
STRING = tth:yyh:hh g: kiiu:
${LINE[1]} is set to tth
${LINE[2]} is set to yyh
${LINE[3]} is set to hh g
${LINE[4]} is set to  kiiu
${LINE[5]} is set to
${LINE[6]} is set to
${LINE[7]} is set to
${LINE[8]} is set to
${LINE[9]} is set to
${LINE[10]} is set to
[ROOT@kif]/root/bin->
```
 :e


----------

