brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: shopt -s autocd lets you change folder by typing only its name

Shell
~/tips/tip-bash-shopt-autocd

shopt -s autocd

Moves into a folder when you type its name, without typing cd.

Zsh users have had this forever and some of them mention it a lot. Bash can do it too, it just ships with it switched off: type a folder name, press Enter, and you are in it, without the cd.

The shell option is autocd. When it is set, a command name that is the name of a folder runs as if you had typed cd in front of it.

shopt -s autocd

Add it to ~/.bashrc to keep it. Then:

$ /mnt/user/appdata
cd -- /mnt/user/appdata
$ ..
cd -- ..
$ pwd
/mnt/user

Bash prints the cd line it ran, so you can see what happened. Typing .. to go up one level is the part I’d use the most, and it works with Tab completion as usual.

It only kicks in when the word is not a command. If a folder has the same name as a program, an alias or a function, that one wins. A folder called test in the current directory won’t be opened when you type test, because test is a shell builtin. Use ./test in that case, or plain cd.

Two more caveats. It is for interactive shells only, so don’t count on it in a script. And it needs bash 4.0 or newer: the /bin/bash that macOS still ships is version 3.2, and there shopt -s autocd gives an “invalid shell option name” error. That’s no problem in the default zsh on a Mac, which has its own setopt autocd, or with a newer bash from Homebrew. On Linux and Unraid the bash is recent enough.

Further reading: The shopt builtin (GNU Bash manual), bash(1) manual page

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link