3

I'm trying to split a string with two words delimited by spaces, and this snippet isn't working for me:

$ cat > test.sh
#/bin/bash
NP="3800 480"
IFS=" "
echo $NP
echo $NP | read VAR1 VAR2
echo "Var1 : $VAR1"
echo "Var2 : $VAR2"
exit 0

And invoking it gives me:

$ chmod 755 ./test.sh && ./test.sh
3800 480
Var1 :
Var2 :

Where I was hoping to see:

3800 480
Var1 : 3800
Var2 : 480

How can a split a simple string like this in a bash script?

EDIT: (Answer I used) Thanks to the link provided by jw013, I was able to come up with this solution which worked for bash 2.04:

$ cat > test.sh
#!/bin/bash
NP="3800 480"
read VAR1 VAR2 << EOF
$NP
EOF
echo $VAR2 $VAR1

$./test.sh
480 3800

4 Answers 4

3

The problem is that the pipeline involves a fork, so you will want to make sure the rest of your script executes in the shell that does the read.

Just add ( ... ) as follows:

. . .
echo $NP | (read VAR1 VAR2
  echo "Var1 : $VAR1"
  echo "Var2 : $VAR2"
  exit 0
)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation. Point and check.
But as a follow-on; how do I 'see' the variables outside the parenthesis?
Well, you could echo them back to the parent and capture them with command substitution. But the two scripts running after the pipeline are both near-identical copies of the original script, so why not just enclose the rest of the script in the parens? I suppose you could also call a shell procedure to execute the remaining functionality. The procedure could be defined outside the parens. (That is, outside the subshell.)
3

With bash, you can use <<< (a "here string", redirect input from a string):

$ NP="3800 480"
$ read VAR1 VAR2 <<< $NP   # NB, variable is not quoted
$ echo $VAR2 $VAR1
480 3800

1 Comment

Intriguing, but unfortunately, I'm using bash 2.04 which gives me the error syntax error near unexpected token '<<<' when used inside a script.
2
#!/bin/bash
NP="3800 480"
IFS=" "
array=($NP)
echo ${array[0]}
echo ${array[1]}

would also work

2 Comments

Good, but a bash-only solution.
"Good, but a bash-only solution." - Which would be fine since the OP was asking for a bash solution. I'd even upvote this if eckes was invoking bash instead of bourne. ;-)
2

Take a look at BashFAQ 024 for more about using read so that you can access the variables later.

My favorite solution (being more portable than the bash-only ones) is the here doc one:

read -r ... << EOF
$NP
EOF

1 Comment

Although you provided the answer I required, the answer to my main question was answered previously. Thanks again though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.