0

It seems the line in Bash

set -- $*

is to re-parse the argument using the new IFS. Example:

try() {
    IFS=:
    set -- $*

    echo 1st, $1
    echo 2nd, $2
    echo 3rd, $3
}

and then

$ try a:b:c
1st, a
2nd, b
3rd, c

because without that line, the output would be

$ try a:b:c
1st, a:b:c
2nd,
3rd,

But this code doesn't work in Zsh. Is there a way to make it work on both Bash and Zsh?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • Don't think `zsh` does word splitting by IFS by default like `bash`. Trying to find a relevant duplicate - Reason for failure in `zsh` - [Variable expansion is different in zsh from that in bash](https://stackoverflow.com/q/6715388/5291015) and for other options - [How do I split a string on a delimiter in Bash?](https://stackoverflow.com/q/918886/5291015) – Inian Dec 08 '20 at 12:27
  • This is sketchy in Bash since an unquoted `$*` is subject to glob expansion. Wildcards like `*` and `?` could expand into one or even multiple file names. – John Kugelman Dec 08 '20 at 12:28
  • 1
    It seems shell scripting is 10 times harder than programming in Ruby or Python... together with what works in Bash may break in Zsh... I am starting to wonder if I should learn more about shell scripting – nonopolarity Dec 08 '20 at 12:30
  • 3
    Target either basic POSIX sh, or a particular shell like bash, zsh, ksh93, etc. Don't try to write one script that works on everything (Unless you stick to what's in sh). – Shawn Dec 08 '20 at 12:35
  • is it true that what works in POSIX sh may not work in Bash or Zsh? Then does that mean in Mac or Linux, we would then use POSIX sh instead of Bash or Zsh? – nonopolarity Dec 08 '20 at 13:38
  • Absolutely. `bash` and `zsh` have *many* non-POSIX extensions. And as far as portability, the version of `bash` you can rely on having on macOS is *much* older than what you can generally assume is available on a given Linux box. – chepner Dec 08 '20 at 19:52

0 Answers0