Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this bash script not splitting the string?

Tags:

bash

scripting

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
like image 434
Jamie Avatar asked Sep 12 '26 12:09

Jamie


1 Answers

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
)
like image 120
DigitalRoss Avatar answered Sep 15 '26 08:09

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!