3

If I type in cd Desktop, no matter what folder the terminal is currently open in, I want it to navigate to /home/bob-ubuntu/Desktop

In my .bashrc file I have the following lines at the bottom:

alias desktop='/home/bob-ubuntu/Desktop'

alias Desktop='/home/bob-ubuntu/Desktop'

and then I source it, but when I type in cd Desktop or cd desktop it still gives the same error?

4
  • Aliases only replace a command (so the first word in the command line) - you can't use them to replace command-line arguments
    – ethanwu10
    Jun 17, 2017 at 18:49
  • How can I do this then?
    – K Split X
    Jun 17, 2017 at 18:50
  • "how can I do it then?" Two ways. You can create a new "desktop" alas/function. desktop(){ cd $HOME/Desktop ; } or you can set the CDPATH variable to "$HOME:." and use "cd Desktop"
    – icarus
    Jun 17, 2017 at 18:54
  • 1
    Just be aware with the second suggestion by @icarus (CDPATH) this would make cd always go to a directory in your home directory over a directory in the current directory.
    – ethanwu10
    Jun 17, 2017 at 19:04

3 Answers 3

3
alias desktop='/home/bob-ubuntu/Desktop'
cd desktop

An alias is for a command name. A parameter to the cd command is not a command name. The alias is not used in this context.

If you type just desktop, this invokes the alias. But by default you'll get an error

bash: /home/bob-ubuntu/Desktop: Is a directory

Add the line shopt -s autocd to your ~/.bashrc so that typing a directory name in command position performs cd to that directory. This way you can change to the directory ~/Desktop by typing just ~/Desktop (instead of cd ~/Desktop) or, with your alias, desktop.

Alternatively, define an alias to a command that works:

alias desktop='cd /home/bob-ubuntu/Desktop'
0
1

There are many ways:

  • You can make a variable for $desktop and/or $D as a shortcut for it.
  • You can alias desktop='cd /home/bob-ubuntu/Desktop'
  • You can use $USER/Desktop
  • You can use $XDG_DESKTOP_DIR if XDG user directories is set.
  • You can add /home/bob-ubuntu to CDPATH environment variable of cd command

But you are really better off just using:

cd ~/Desktop

Tilda shouldn't hurt! :D

Note that you can also use tilda to switch to $HOME directories of many users in your system as follows:

cd ~root
ls ~ftp
echo ~nobody
0

As icarus suggested in the comments, one simple way is to create an alias that does cd ~/Desktop

However if you really want cd to behave this way, you can alias a function to cd that handles checking if the directory is Desktop:

_cd () {
  if [ "$1" == "Desktop" ]; then
    cd ~/Desktop
  else
    cd $1
  fi
}
alias cd="_cd"

However this also causes tab completion for cd to break

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .