JP Vossen via plug on 26 Apr 2023 13:28:08 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Splitting strings in bash


On 4/26/23 04:09 PM, Walt Mankowski wrote:
On Wed, Apr 26, 2023 at 04:00:24PM -0400, JP Vossen wrote:
On 4/26/23 03:46 PM, Walt Mankowski via plug wrote:
Hi all,

I've got a question about splitting strings in a bash shell
script. Let's say I've got a string

STR='dog cat'

I'd like to split that on the space into two variables, foo and bar. I
tried this

echo $STR | read foo bar

but it doesn't work. On the following line foo and bar are back to
their original values. Then, after looking through the bash manpage
for an alternative, I tried this instead

read foo bar <<< $STR

That DID work!

So that solves my problem, but I'm still confused. Those two commands
seem to me like they should be identical. Why doesn't the first one work?

Because the `|` causes a sub-shell, which cannot modify the environment in the parent shell.  That's frustrating as hell, and causes subtle little things like you ran into a lot. :-/

Thanks! It makes sense after I thought about it for a bit.

BTW did you mean to just send this to me instead of the list?

No, I meant the list.  It's been a LONG week already...

Later,
JP
--  -------------------------------------------------------------------
JP Vossen, CISSP | http://www.jpsdomain.org/ | http://bashcookbook.com/

___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug