Bash – What Does [ -t 1 ] Check?

bashshelltestzsh

I just found a way to start zsh when I start the bash on Windows from

https://www.howtogeek.com/258518/how-to-use-zsh-or-another-shell-in-windows-10/.

It recommended to add following code at the last of .bashrc.

# Launch Zsh
if [ -t 1 ]; then
exec zsh
fi

What does [ -t 1 ] mean?

Is it just true?

Then, can I just do this?

exec zsh

Best Answer

[] is shortcut of test command.

According to man test:

-t FD
True if FD is a file descriptor that is associated with a terminal.

So if you running bash as interactive shell (terminal - see this thread for terminology explanation), bash will be replaced by zsh.

More about .bash* files:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

When a login shell exits, bash reads and executes commands from the files ~/.bash_logout and /etc/bash.bash_logout, if the files exists.

When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.

Stéphane Chazelas comment:
Note that a shell can be interactive without stdout being a terminal, and a shell can be non-interactive with a terminal on stdout (like anytime you run a script within a terminal without redirecting/piping its output), and bash can read .bashrc even when not interactive (like in ssh host cmd where bash is the login shell of the user on host, or bash --login -c 'some code'). case $- in *i*)... is the correct way to test if a shell is interactive.