Timeline for How to split one string into multiple variables in bash shell?
Current License: CC BY-SA 3.0
10 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Jul 9, 2020 at 5:01 | comment | added | tripleee |
You can do something like oldIFS=${IFS-__unset__} but restoring from that is arguably clunky at best.
|
|
Jul 8, 2020 at 23:04 | comment | added | Daniel Andersson | @Binarus Good point -- mywiki.wooledge.org/BashPitfalls #49 has some words about this. In practice I like to use subshells for things like this (the last suggestion in the link), temporary options, etc., but sometimes that is too limiting. | |
Jun 23, 2020 at 18:41 | comment | added | Binarus |
@DanielAndersson I got your point, but this will do the wrong thing if IFS is originally unset. I don't know whether that could happen in a normal bash environment, but I am meaning my comment in a more general sense. Setting a variable to a custom value and restoring it later is surprisingly complicated if it is not known in advance whether or not that variable originally is set.
|
|
Oct 11, 2019 at 16:56 | comment | added | Léa Gris |
Maybe add a set -f to disable pathname expansion before set -- $STR , or it will capture paths files names if $STR contains patterns.
|
|
Mar 27, 2015 at 7:00 | comment | added | tripleee |
@DanielAndersson That's a good and common workaround as well if you don't want to or cannot use a function with a local IFS (which isn't entirely portable anyway).
|
|
Mar 27, 2015 at 6:46 | comment | added | Daniel Andersson |
This is a really sweet solution if we need to write something that is not Bash specific. To handle IFS troubles, one can add OLDIFS=$IFS at the beginning before overwriting it, and then add IFS=$OLDIFS just after the set line.
|
|
Jun 19, 2013 at 13:25 | comment | added | tripleee |
No, don't use a useless echo in backticks.
|
|
Jun 19, 2013 at 8:08 | comment | added | Sigg3.net |
I used triplee's example and it worked exactly as advertised! Just change last two lines to <pre> myvar1=echo $1 && myvar2=echo $2 </pre> if you need to store them throughout a script with several "thrown" variables.
|
|
May 9, 2012 at 19:20 | comment | added | Rob I |
Nice - I knew about $IFS but hadn't seen how it could be used.
|
|
May 9, 2012 at 17:57 | history | answered | tripleee | CC BY-SA 3.0 |