What is the difference between "cd \" and "cd /" commands in ubuntu terminal?

On giving cd \, I get the > symbol while cd / changes the ~ sign in my directory to /.

Also ls command shows me directories like dev, root, usr in case of cd /.


Solution 1:

In Bash, your shell, the \ (backslash) denotes an escape character. This should be used in cases where you want to escape characters like spaces, quotes and other characters meaningful to the shell syntax, but you want to have it propagate as data to the command you're running. By having this as the last character on the line you're escaping the newline and Bash is waiting for further input (multiple lines).

/ is just a forward slash (meaning directory separator). With just / this means the root, so for example ls / lists the contents of the root. By changing the working directory to /, the indicator in your shell also changes from ~ (short for home directory, e.g. /home/gert/) to the directory you're in then (/).


Demo

$ touch a filename with spaces
$ ls -l
total 0
-rw-rw-r-- 1 gert gert 0 Jul  1 02:33 a
-rw-rw-r-- 1 gert gert 0 Jul  1 02:33 filename
-rw-rw-r-- 1 gert gert 0 Jul  1 02:33 spaces
-rw-rw-r-- 1 gert gert 0 Jul  1 02:33 with

Oh noes, it was my intention to create one file with the name a filename with spaces. So, here we use the \ to escape the spaces. This prevents the shell to provide four arguments to touch, but instead provide a single one with the spaces included.

touch a\ filename\ with\ spaces

$ touch a\ filename\ with\ spaces
$ ls -al
total 24
drwxrwxr-x  2 gert gert  4096 Jul  1 02:35 .
drwxrwxr-x 55 gert gert 20480 Jul  1 02:33 ..
-rw-rw-r--  1 gert gert     0 Jul  1 02:35 a filename with spaces

Of course, by using quotes (touch "a filename with spaces") one can achieve the same thing.

It is also used to declare special characters like newlines:

$ echo -e "bla\nnewline" # \n means a newline character
bla
newline

We need the -e option here for echo, because as the manpage put it: -e enable interpretation of backslash escapes.

Solution 2:

If you enter a backslash you can enter your comand on multiple lines. This is what the prefix '>' stands for.

Solution 3:

The > sign means that the prompt is waiting for you to input more, because the previous command was incomplete. You can reproduce this with anything, not just cd. Just type whateveryouwant\, and you'll get >.

The part where you see the ~ denotes the current working directory. To change the working directory, you use the command cd, which means change directory (folder). So if you do cd /, it changes the directory to /. If you do cd /usr/bin, it will change to /usr/bin, and so on.

ls is a command to list what's in the current directory/folder. So, if you do cd / (meaning you've changed the directory to /), ls would list whatever files and folders in there. If you do cd /etc/ and then ls, it would list whatever files and folders that are in /etc/, and so on.