12

The thing is that sometimes I type cd by mistake and that take me to the home directory.

e.g. I'm in a directory that have a hidden directory and a visible directory, I quickly press cd+tab and that takes me to the home directory

muru
  • 207,228

4 Answers4

14

Use gedit ~/.bashrc and insert these lines at the bottom:

cd() {
    [[ $# -eq 0 ]] && return
    builtin cd "$@"
}

Open a new terminal and now when you type cd with no parameters you simply stay in the same directory.


TL;DR

If you want to be really elaborate you can put in a help screen when no parameters are passed:

$ cd

cd: missing operand

Usage:

cd ~            Change to home directory. Equivelent to 'cd /home/$USER'

cd -            Change to previous directory before last 'cd' command

cd ..           Move up one directory level

cd ../..        Move up two directory levels

cd ../sibling   Move up one directory level and change to sibling directory

cd /path/to/    Change to specific directory '/path/to/' eg '/var/log'

The expanded code to accomplish this is:

cd() {
    if [[ $# -eq 0 ]] ; then
        cat << 'EOF'

cd: missing operand

Usage:

cd ~            Change to home directory. Equivelent to 'cd /home/$USER'

cd -            Change to previous directory before last 'cd' command

cd ..           Move up one directory level

cd ../..        Move up two directory levels

cd ../sibling   Move up one directory level and change to sibling directory

cd /path/to/    Change to specific directory '/path/to/' eg '/var/log'

EOF return fi

builtin cd &quot;$@&quot;

}

6

If it's tab completion that's causing this, one option is to make the completion cycle through entries immediately. This can be done using readline's menu-comple option instead of the default complete:

bind 'tab: menu-completion'

Then, in my home directory, for example:

$ cd <tab> # becomes
$ cd .Trash

Of course, even then you'd have to read what you're executing.

muru
  • 207,228
4

Here's how I put the current dir and user in my windows title - You can adapt it to your need, but cd -, equivalent to cd $OLDPWD is a better solution.

From my ~/.bashrc:

# from the "xttitle(1)" man page - put info in window title
update_title()
{
    [[ $TERM = xterm ]] || [[ $TERM = xterm-color ]]  && xttitle "[$$] ${USER}@${HOSTNAME}:$PWD"
}

cd()
{
    [[ -z "$*" ]] && builtin cd $HOME
    [[ -n "$*" ]] && builtin cd "$*"
    update_title
}
waltinator
  • 37,856
3

The problem here is not cd, and it's not fixed by technology.

The problem is you, and it's fixed by patience!

If you frequently find yourself typing and submitting commands that you did not want, practice slowing down. Take a breath, read what you're typing, and double-check it before pressing enter. Think it through. Don't rush.

You'll find that this approach not only solves the problem at hand, but other far worse problems that you are going to encounter if you continue down your current path.