Shell Script TIL

Posted on April 28, 2023

I spent way more time on a problem than I wish to admit to myself.

The snippet I spent so much time on, was this:

bash

xrandr --output ${connected_monitors[2]} --mode 2560x1440 --right-of eDP1 #connected_monitors is an array that contains the display options available

Nothing too complicated which makes it harder to see where the problem is, since there is no way to decompose this any further. This commands worked fine when typed in the terminal application running z-shell. But when I run it in the script it wasn’t producing the desired result.

Try running the below snippet in bash and zsh

arr=("a" "b")
echo ${arr[1]}

Can you guess what the problem could have been now?

The outputs from zsh and bash are the following:

zsh: a

bash: b

Turns out, that the issue was in the array indexing. Since the shebang line in the script was #!/bin/bash.

Bash starts the array indexing from 0 where as in zsh it starts from 1. I wanted to reference the second element in the array, as you can tell and was working perfectly fine in zsh. But becuase I was invoking it in bash when running from script it returned empty. Changing ${connected_monitors[2]} to ${connected_monitors[1]} fixed my issue.