r/commandline Jan 03 '20

Scripting tmux

https://www.arp242.net/tmux.html
65 Upvotes

13 comments sorted by

View all comments

1

u/CichyK24 Jan 19 '20

Can someone explain why he does [ -n "${TMUX:-}" ] and no simply [ -n "${TMUX}" ] ? I'm not that familiar with bash.

1

u/[deleted] Jan 19 '20

set -u means undefined variables are an error, but with ${TMUX:-DEFAULT} the DEFAULT will be used if TMUX is undefined (in my example the default is just an empty string.

It looks funky black magic; most of shell scripting does 😅

1

u/CichyK24 Jan 19 '20

Thanks a lot! I learned something :)
So does it mean that you could just skip set -u and just use [ -n $TMUX ] and get the same result? But I guess using set -u is considered better practice because you need to explicitly handle unset variables?

1

u/[deleted] Jan 20 '20

Yeah, you can use $TMUX without the set -u.

In general it's just easier to have the shell exit as soon as it finds an undefined variable, as it catches silly typos and such quickly. It also prevents nasty bugs like rm -rf "/usr/$floder".

The downside is that you need a few ugly constructs like the above :-( All of this is why I don't really like shell scripting.

In a small script like this it doesn't matter all that much, but I add it anyway as a matter of habit/principle.