Using zsh 5.8.1 (x86_64-apple-darwin21.0), I have a script that relies on zsh's default 1-based array indexing, and I want to ensure that any previous user setting doesn't interfere with that. The best course of action seems to be to store the user's current KSH_ARRAYS setting, then unset this option, then reset the option to its original setting once I'm done. I have the following:
#!/usr/bin/env zsh if [[ -o ksharrays ]]; then echo "setting ksharrays_is_set to 1..."; ksharrays_is_set=1; else echo "setting ksharrays_is_set to 0..."; ksharrays_is_set=0; fi unsetopt KSH_ARRAYS; # here is where my script runs if [[ ksharrays_is_set -eq 1 ]]; then echo "setting the ksharrays option..."; setopt ksharrays; fi To test this, I run setopt ksharrays in my terminal, followed by my script. However, I'm still seeing setting ksharrays_is_set to 0... echo'ed to the terminal.
When I add setopt ksharrays to line 2 (directly under the shebang), I see setting ksharrays_is_set to 1... and setting the ksharrays option... as expected.
Why is the option not being picked up when I set it in the terminal, but it is when I set it in the script?
EDIT: I also tried adding setopt ksharrays to both my ~/.zshrc and ~/.zshenv and sourceing those files, followed by running the above script. This, too, resulted in setting ksharrays_is_set to 0... as the output, rather than the expected output. I confirmed that the setopt command took effect by running it without args in my terminal:
$ setopt combiningchars interactive ksharrays login monitor promptsubst shinstdin zle EDIT 2: I add echo $(setopt) to the top of the script. The only thing that prints out is nohashdirs. I don't see combiningchars, interactive, or any of the other options that appear when I run setopt without args directly in my terminal.
export ksharraysin your terminal for it to be passed into the script?ksharraysis a shell option, not an environment variable.zshshell options would influence any script run within that shell. If that's not the case, i.e. if options in interactive mode are separate from options inside a script, let me know. I'm new to shell scripting so that could be one of my "unknown unknowns". If so, I'd be curious to read more about that from the docs if you can point me in the right direction. Note that the zsh docs on options don't appear to discuss this one way or the other- that's the first place I checked before posting here.