开发者

Why is this bash script not splitting the string?

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 gi开发者_如何学Cves 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


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
)


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


#!/bin/bash
NP="3800 480"
IFS=" "
array=($NP)
echo ${array[0]}
echo ${array[1]}

would also work


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜