Bash - create, change and destroy

Now we get to create directories, change their name, create more and then destroy them.

These are fundamental skills in administering our server.

We ended the last article looking at what was is our home directory. Let's create a directory there called playground. The command for this is 'mkdir':

mkdir playground

A quick 'ls' will show the newly created directory:

Note how it was created in the directory we were working in. If we wanted to create a directory in the public_html folder, we could do a 'relative path':

mkdir public_html/playground

or an 'absolute' path:

mkdir /home/paul/public_html/playground

The difference should be clear: one was created as a 'relative' path to where we were working and with the other, it doesn't matter where we were working as it was created using an absolute path - created from the root directory of the server. We could give the latter command from anywhere within the server and the playground directory would be created in the same place.

Unfortunately, we got the name wrong. It wasn't playground we wanted but sandbox. To rename the directory we simply move it from the old name to the new name. Let's do that and have a look to see if it worked:

mv playground sandbox
ls

That's better. But why didn't we use the command 'rename'? Well, have a look at the manual for 'rename' ('man rename'). Rename requires regular expressions and is not actually used for this type of work. If you think about it in 'computer' terms, we are moving the directory: from playground to sandbox.

The trouble is, we now realise we did need the playground directory and we need a directory inside that one called 'test'. Well, we could just give the 'mkdir' twice, once to create the playground directory and then again to create the test one. However, that seems like a lot of work - what if we need 5 or 10 levels of directories? Let's call on the man!

man mkdir

Much to our delight we see the option 'p' is available to us. Let's give that a go:

mkdir -p playground/test

Let's check if the test directory was created inside the playground directory:

ls
ls playground/

Success! Wanting to do something else now, we are loathe to leave our server littered with useless directories so before we log off let's delete the new folders:

rmdir sandbox
rmdir playground

Hmm. One command worked and one didn't. The rmdir command will only work if the directory is empty and there's the test folder inside playground. Let's try another way:

rm -r playground

That's it (if you are unsure about the 'rm -r playground' then ask the man - he'll tell you -r means 'recursive').

The next article will concentrate on creating files, adding content to existing ones and one mistake not to make!

PickledOnion

Digg it | del.icio.us | reddit | StumbleUpon

Comments are closed for this article.