1

I have the following bash code:

FULLSTR="/FOO/BAR/QUX"
IFS=/
ARY=($FULLSTR)

What I want to do is to concatenate the 2nd and 3rd element of ARY with / and assigned it into a variable. The end result I hope to get is /BAR/QUX.

But why this doesn't work:

NSTR=/${ARY[2]}/${ARY[3]}
echo $NSTR

It produces:

 BAR QUX

What's the right way to do it?

ruakh
  • 175,680
  • 26
  • 273
  • 307
littleworth
  • 4,781
  • 6
  • 42
  • 76
  • And if you quote your variables? For example, `NSTR="/${ARY[2]}/${ARY[3]}"; echo "$NSTR"`? Always quote your variables, unless you know precisely why you don't want to. – ghoti Oct 29 '18 at 03:54

2 Answers2

3

The issue is in your echo $NSTR command: IFS is still set to /, so when $NSTR undergoes word-splitting and file-name expansion, the stuff on either side of a / becomes separate arguments to echo.

To fix this, I recommend finding a better way to set ARY to begin with, rather than starting with $FULLSTR. Parameter-expansions such as $FULLSTR should essentially always be quoted, because you essentially never want word-splitting and filename-expansion. (In your case you do want the word-splitting . . . but not the filename-expansion.)

If that's not an option — if your only way to set ARY is by splitting $FULLSTR — then you can write something like this:

OLDIFS="$IFS"
IFS=/
ARY=($FULLSTR)
IFS="$OLDIFS"

NSTR="/${ARY[2]}/${ARY[3]}"
echo "$NSTR"

Or, better yet, you can set NSTR directly based on $FULLSTR, and avoid ARY except when you have no choice:

NSTR="/${FULLSTR#/*/}"
echo "$NSTR"
ruakh
  • 175,680
  • 26
  • 273
  • 307
0

you do not need to concatenate and yes cut!

FULLSTR="/FOO/BAR/QUX"

echo ${FULLSTR#/FOO}

Output:

/BAR/QUX

so has your result !!

agc
  • 7,973
  • 2
  • 29
  • 50
noob
  • 9
  • 2