7

I just switched from Ubuntu to macOS (due to work reasons). And I wanted to transfer my bash aliases to zsh, but they are not working completely.

alias HPC1='ssh -l [username] [server1]'
alias HPC2='ssh -l [username] [server2]'
HPC[0]="HPC1"
HPC[1]="HPC2"
alias HPC='eval "${HPC[$RANDOM % 2]}"'

HPC1 connects to server1 and HPC2 connects to server2. HPC should connect to either server1 or server2 randomly. It works within bash. In macOS (zsh) only the aliases HPC1 and HPC2 work, but not HPC. Is the syntax different there?

Thanks for helping me out :).

8
  • zsh array indizes start with 1, see stackoverflow.com/questions/50427449/…
    – nohillside
    Jul 17, 2022 at 18:05
  • Related apple.stackexchange.com/questions/361870/…
    – nohillside
    Jul 17, 2022 at 18:38
  • If you have a complex Bash setup it might be worth installing and using an upto date bash using macports or homebrew. The package managers would also help if you needed any other unix programs that you used on Linux
    – mmmmmm
    Jul 18, 2022 at 8:31
  • 1
    In zsh, HPC[0]="HPC1" should result in the error message assignment to invalid subscript range. If you don't get this error message, it means that the code either is not executed by zsh, or maybe by a zsh which is configured to run in Korn-shell compatible mode. Jul 18, 2022 at 9:57
  • 1
    In general, don't try to use identical code for bash and zsh; there are too many differences, and not only in the array handling. A better approach would be to take the bash code as inspiration and write the zsh code from scratch. Jul 20, 2022 at 6:23

1 Answer 1

9

bash starts array indexes at 0, zsh at 1.

One slightly strange-looking way to overcome this is

server_list=(HPC1 HPC2)
alias HPC='ssh -l username ${server_list[(($RANDOM % 2 - 2))]}'

This puts the server names into a shell array, and then randomly picks the first or the second from the end of the list ($RANDOM % 2 - 2 is either -1 or -2).

3
  • 1
    You could also setopt KSH_ARRAYS, but that changes other semantics in addition to the zero-vs-one array indexing, so you should read the documentation before enabling it.
    – Kevin
    Jul 18, 2022 at 6:02
  • 1
    Brilliant! In that way, it would select an array item starting from the bottom.
    – apaderno
    Jul 18, 2022 at 10:52
  • @apaderno That is, if you envision arrays as growing from top to bottom. I envision them growing from left to right, so the negative indices operate on the items counted from the right.
    – jrw32982
    Jul 19, 2022 at 17:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .