0

I am using a zsh shell and set an environmental array. Like this:

➜  ~ a=(1 2 3 4)
➜  ~ echo $a[3]
3
➜  ~ bash
%n@%m:%~%# b=(1 2 3 4 5)
%n@%m:%~%# echo $b[3]
1[3]
%n@%m:%~%# echo ${b[3]}
4
%n@%m:%~%# exit
exit
➜  ~ echo ${a[3]}
3
➜  ~

Colorful title is zsh while another is bash, they obviously have an opposite result. What I have read from a book about shell is like what the bash acts. So is zsh wrong? And if I write scripts for bash, would it got trouble in zsh environment? I am a newcomer for Linux , thanks if answer.

  • See https://unix.stackexchange.com/a/252405/102168. The only time you will get in trouble is if you don't add a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) to your scripts. Adding that line tells your shell which interpreter to use, so e.g. even if you are running `zsh` as your primary shell, you can still run scripts under `bash` with `#!/usr/bin/bash`. – 0x5453 Feb 21 '18 at 14:28
  • @0x5453 Or better, see https://stackoverflow.com/questions/10376206/what-is-the-preferred-bash-shebang. – Thomas Feb 21 '18 at 14:32
  • 1
    Arrays are not standard, so each shell can implement them as they please. `zsh` is neither right nor wrong; it is just *different* from `bash`. – chepner Feb 21 '18 at 14:43
  • 1
    In addition to the reference @0x5453 gave about 1 vs 0 array indexing. The reason `$b[3]` gave you `1[3]` is because bash parsed it as `$b` followed by the plain string `[3]`. As you saw, the curly braces forced a specific parsing that included the `[3]` in the variable name. I would highly recommend *always* using curly braces whenever referencing any shell variables, even simple ones like `$foo`. If `foo=cool`, and you did: `other=$foo_bar`, expecting `other=cool_bar`, you might get surprised if `foo_bar` had also been defined in the shell. – onlynone Feb 21 '18 at 14:44
  • See also https://stackoverflow.com/questions/6715388/variable-expansion-is-different-in-zsh-from-that-in-bash though not strictly a duplicate. The TLDR as others have already commented is that they are different; don't expect them to be identical. – tripleee Feb 21 '18 at 14:52

1 Answers1

0

To answer the main question, as a rule, scripts for zsh should be written separately from those for bash. bash and zsh are both themselves, and should not be treated as two versions of the same product.

There are two reasons for what happend in your example:

  1. Indexing

    • zsh indexes arrays from 1 to some n
    • bash indexes arrays from 0 to n-1
  2. Syntax

    • zsh uses $array[index] syntax
    • bash uses ${array[index]} syntax, and understands $array as access to the first element of the array, so if it is followed by anything else, the remainder is treated as a literal (that's where 1[3] came from)
Arusekk
  • 827
  • 4
  • 22