2011-09-03

Linux: A Beginner's Guide, First Steps pt.2








Welcome back!  I hope you've gotten good and bored with the last bit of stuff I had you practicing.  Just as with learning a new language (I've recently decided to learn Dutch) and music, nothing can be so vital as practice.  Last time we talked about moving around the filesystem, looking into directories, and how to create directories.  Today we are going to talk about renaming, copying, moving, and deleting folders and files in the terminal.

Why do I need to learn this?


I'll answer this question with a bit of a story.  When I was nine (1993) I had decided that I was going to share the Linux world with a friend of mine.  Slackware had literally just come out to the public and I was lucky enough to get a copy of it.  My buddy (taken in by all the uber cool hacker news and not wanting to risk not being "cool") was totally happy with trying it out.  He was eleven years old.  Now, keep in mind, people were a lot different when it came to computers back then.  Personal computers were pretty limited to rich people or people who worked in the field, but were starting to make their way into mainstream society.

Needless to say, we didn't bother asking his mom if we had permission, we were too "cool" for that.  Now, my friend had no concept of what Linux was, for him, it was just like the Mac machines that we booted up in school.  There would be graphics and all of this other fun stuff to play with, right? Wrong!  Nowadays you kids have it easy.  There are installers that do it all for you (Arch and Gentoo are the only two mainstream distros that I know of that are still semi-manual).  I booted up the image and we were off.  Long story short, I got Slackware installed on his machine and hooked him up with twm, a very old but stable window manager for Linux, and even got some source packages together for him so that he could go online.

All was well in the world, right? Nope!  See, his mom worked with my mom, a cubicle wall apart.  When my mom found out what I was doing (my brothers were snitches) both moms were livid.  Mine more than his (she though open source software was stealing).  His mom came home, and was at least happy that we backed up her files and left her with a working system.  So she ran with it.  Her only real response was "You just make sure that if it breaks, you can fix it!"  We were in the clear! Until a week later...

You see, my buddy's mom wasn't the brightest person in the world, and my buddy even less so.  She managed to uninstall twm without knowing how to get it back.  No biggy, right?  Big fat wrong!  I thought that my friend had been paying attention when I showed him how to install stuff and fix things.  He wasn't.  I had neglected to teach him some very basic things, like how to use something other than a GUI.  Because of this, we were both grounded until I could get their computer back in working order.  What made matters worse was, there's a lie in there.  We were grounded until I got it back in working order, I was grounded until my mom said so.  Gotta love parents that work in Contract Law Translation.  (Not!)

So you see, while now we have GUI tools that can pretty much do all of this stuff for you, back then if something happened to the GUI and you didn't know the command line, you were pretty much screwed.

I don't want you to be screwed, you don't want you to be screwed, so let's not get screwed.  Besides, "'Tis better to have and not need than to need and not have."


Creating Files


You know how when you touch something it leaves a fingerprint?  Good.  You know how I said that everything in Linux is a file?  Great! You've been paying attention.  Well, in Linux it's really easy to create a file.  You just have to "touch" something.  In this case, that something is the filesystem.  We are going to leave a "fingerprint" on your filesystem using the "touch" command.  If you haven't done so already, please open your terminal and follow along.  Assume that after each command that I want you to press "Enter" (Carriage Return) unless otherwise stated.

(darthlukan@SithCouncil)$ touch me
(darthlukan@SithCouncil)$

Don't worry, in Linux, no news is good news (usually), so the fact that you were returned to an empty prompt is good.  What did we just do here other than allude to a sick joke?  We just used the command "touch" to create a file named "me".  This is a common thing in Linux (not touching yourself!) that you should get used to.  In Linux, you type a command (touch) and what follows is generally either an argument, the name of a file (me) or some other instruction.  Now, go ahead and type "ls" (without quotes) and hit enter.  You should see somewhere in that list a file named "me".  Pretty easy huh?

Now, I want you to open your file manager, the GUI one that came with your system, and I want you to do the same thing.  If you right-click on an empty space in the current folder of your file manager, you should have a context menu open up (kinda like in Windows).  One of the options should be "New...".  Go ahead and create a new file named "you".  That probably took a few clicks, huh?  I want you to think back to when I showed you how to make folders (directories, mkdir command).  Remember how we were able to make a whole bunch of folders all at once?  Can you do the same in your GUI file manager? No, you can't (there are file managers that allow this, but they are beyond the scope of this document and are more advanced than you probably want to get at the moment).

Go back to your terminal and type the following:

(darthlukan@SithCouncil)$ touch him her them
(darthlukan@SithCouncil)$

Pretty cool huh?  Can you see where this is valuable in saving time?  I can!  We have just one problem now, but this problem will be expanded on (along with the answer to the problem) in the next section.


Moving Files


Isn't this a fine mess?  We now have files left rampant in our /home directory.  I don't know if you have OCD or not, but I do, and disorderly stuff mucking around in my realm of order and perfection irritate the living day lights out of me.  Let's clean up a little!  I want you to create a directory using your terminal called "pronouns".  If you have forgotten how to do this, then you didn't do your homework like I asked in the previous section.  If you did do your homework, you've already made the folder while reading, so I'll move on.

(darthlukan@SithCouncil)$ mv you pronouns
(darthlukan@SithCouncil)$ mv me pronouns && mv her pronouns
(darthlukan@SithCouncil)$ mv -t pronouns him them
(darthlukan@SithCouncil)$ cd pronouns
(darthlukan@SithCouncil)$ ls

her  him  me  them  you
(darthlukan@SithCouncil)$

This is the part where I want you to look at what we just typed and I want you to think about it.  Don't skip down further to the next section! Seriously, look at what we did.  Have you caught it? Good!  For those still wondering why I made you re-read what we just did, it's because I taught you something in a somewhat sneaky way.  Remember when you were a kid and some older relative told you "there's more than one way to skin a cat?"  They were teaching you about Linux and didn't even know it!  In Linux there are multiple ways to do the same thing.  You've got the first way, do it one at a time.  The second way, use "&&" to link way number one and repeat it (that's not actually what && does, but for now it will do).  Third, we use an argument/option to do what we want in one command.

How did I know that using "-t" and reversing the order of the folder with the files would copy them properly? I'm awesome that way.  Actually, I know this because at one time I was taught the most important lesson I think that I have ever learned (other than "Microsoft is the devil"), that was " --help and -h will save your life!"  Go ahead and try it!

(darthlukan@SithCouncil)$ mv --help
Usage: mv [OPTION]... [-T] SOURCE DEST
  or:  mv [OPTION]... SOURCE... DIRECTORY
  or:  mv [OPTION]... -t DIRECTORY SOURCE...
Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options too.
      --backup[=CONTROL]       make a backup of each existing destination file
  -b                           like --backup but does not accept an argument
  -f, --force                  do not prompt before overwriting
  -i, --interactive            prompt before overwrite
  -n, --no-clobber             do not overwrite an existing file
If you specify more than one of -i, -f, -n, only the final one takes effect.
      --strip-trailing-slashes  remove any trailing slashes from each SOURCE
                                 argument
  -S, --suffix=SUFFIX          override the usual backup suffix
  -t, --target-directory=DIRECTORY  move all SOURCE arguments into DIRECTORY
  -T, --no-target-directory    treat DEST as a normal file
  -u, --update                 move only when the SOURCE file is newer
                                 than the destination file or when the
                                 destination file is missing
  -v, --verbose                explain what is being done
      --help     display this help and exit
      --version  output version information and exit

The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.
The version control method may be selected via the --backup option or through
the VERSION_CONTROL environment variable.  Here are the values:

  none, off       never make backups (even if --backup is given)
  numbered, t     make numbered backups
  existing, nil   numbered if numbered backups exist, simple otherwise
  simple, never   always make simple backups

Report mv bugs to bug-coreutils@gnu.org
GNU coreutils home page:
General help using GNU software:
For complete documentation, run: info coreutils 'mv invocation'
(darthlukan@SithCouncil)$

Read that help output.  Commit at least the first portion to memory if you can.  If you can't, just remember that "--help" could save your life!  On to the next section.


Renaming Files

Just as Ron White told you the story of him being called "Tater" so that he could give you another great joke about being drunk in public, I told you about how to move files with "mv" so that I could show you how to rename them.  Go ahead and type the following into your terminal:

(darthlukan@SithCouncil)$ mv him he
(darthlukan@SithCouncil)$ ls
he  her  me  them  you
(darthlukan@SithCouncil)$

Nifty!  So what did we do?  We used the "move" command to rename a file, right?  Not exactly.  Here's the more complicated explanation.  What we did was pick up the file "him" and then placed him somewhere issuing him the new name "he".  Although he's in the same folder, he's not in the same place on the disk that he was earlier.  So we really did move him, just not out of the folder.  There really isn't much more to say here, so we can move on to the next section.  (We could go into more complicated methods of file renaming, but they require more explaining than is really appropriate for this guide).



Copying Files and Folders

Let's have some fun.  So, we all know that maintaining backups is important, right?  If you didn't know that, consider yourself educated!  Backup backup backup backup backup! Never forget that.  Well, what's a backup?  It's a copy of something.  Tonight/today you will learn the basics of backups.  Look at that! Two birds with one stone, I'm on a roll tonight. :)

Go ahead and type the following into your terminal:

(darthlukan@SithCouncil)$ cd 
(darthlukan@SithCouncil)$ mkdir grammar
(darthlukan@SithCouncil)$ cp -r pronouns grammar
(darthlukan@SithCouncil)$ ls grammar
pronouns
(darthlukan@SithCouncil)$

Whoa! That was pretty quick huh?  So what did we do?  Go ahead and type:

(darthlukan@SithCouncil)$ cp --help
Usage: cp [OPTION]... [-T] SOURCE DEST
  or:  cp [OPTION]... SOURCE... DIRECTORY
  or:  cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options too.
  -a, --archive                same as -dR --preserve=all
      --attributes-only        don't copy the file data, just the attributes
      --backup[=CONTROL]       make a backup of each existing destination file
  -b                           like --backup but does not accept an argument
      --copy-contents          copy contents of special files when recursive
  -d                           same as --no-dereference --preserve=links
  -f, --force                  if an existing destination file cannot be
                                 opened, remove it and try again (redundant if
                                 the -n option is used)
  -i, --interactive            prompt before overwrite (overrides a previous -n
                                  option)
  -H                           follow command-line symbolic links in SOURCE
  -l, --link                   link files instead of copying
  -L, --dereference            always follow symbolic links in SOURCE
  -n, --no-clobber             do not overwrite an existing file (overrides
                                 a previous -i option)
  -P, --no-dereference         never follow symbolic links in SOURCE
  -p                           same as --preserve=mode,ownership,timestamps
      --preserve[=ATTR_LIST]   preserve the specified attributes (default:
                                 mode,ownership,timestamps), if possible
                                 additional attributes: context, links, xattr,
                                 all
      --no-preserve=ATTR_LIST  don't preserve the specified attributes
      --parents                use full source file name under DIRECTORY
  -R, -r, --recursive          copy directories recursively
      --reflink[=WHEN]         control clone/CoW copies. See below
      --remove-destination     remove each existing destination file before
                                 attempting to open it (contrast with --force)
      --sparse=WHEN            control creation of sparse files. See below
      --strip-trailing-slashes  remove any trailing slashes from each SOURCE
                                 argument
  -s, --symbolic-link          make symbolic links instead of copying
  -S, --suffix=SUFFIX          override the usual backup suffix
  -t, --target-directory=DIRECTORY  copy all SOURCE arguments into DIRECTORY
  -T, --no-target-directory    treat DEST as a normal file
  -u, --update                 copy only when the SOURCE file is newer
                                 than the destination file or when the
                                 destination file is missing
  -v, --verbose                explain what is being done
  -x, --one-file-system        stay on this file system
      --help     display this help and exit
      --version  output version information and exit

By default, sparse SOURCE files are detected by a crude heuristic and the
corresponding DEST file is made sparse as well.  That is the behavior
selected by --sparse=auto.  Specify --sparse=always to create a sparse DEST
file whenever the SOURCE file contains a long enough sequence of zero bytes.
Use --sparse=never to inhibit creation of sparse files.

When --reflink[=always] is specified, perform a lightweight copy, where the
data blocks are copied only when modified.  If this is not possible the copy
fails, or if --reflink=auto is specified, fall back to a standard copy.

The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.
The version control method may be selected via the --backup option or through
the VERSION_CONTROL environment variable.  Here are the values:

  none, off       never make backups (even if --backup is given)
  numbered, t     make numbered backups
  existing, nil   numbered if numbered backups exist, simple otherwise
  simple, never   always make simple backups

As a special case, cp makes a backup of SOURCE when the force and backup
options are given and SOURCE and DEST are the same name for an existing,
regular file.

Report cp bugs to bug-coreutils@gnu.org
GNU coreutils home page:
General help using GNU software:
For complete documentation, run: info coreutils 'cp invocation'

Don't worry, there's a very good reason why I keep pasting the "--help" output, but we'll get to that in a minute.  

What we just did was copy a directory (and its contents) into another directory. If we only wanted to copy the files themselves, we would have stayed inside the "pronouns" directory and copied the files, but that would have required a lot of typing.  Instead what we did was use the "-r" option to copy the folder and its contents recursively.  That means that the copy command sees what's inside of "pronouns", notes it, and starts making copies of the folder itself and then the files, placing the whole thing inside the destination "grammar".  

On to the next section minions!



Deleting files and folders


I want to start this section with a warning.  The command that I'm about to show you comes in many different formats, some of which are used deliberately by kids, criminals, and mean people (but mostly just by kids) to make an otherwise unwitting individual delete their system!  So before I show you the right way, I want you to commit the wrong way to memory so that you do not make the mistake that many people have made in the past (and still do unfortunately).

Plain:  rm -rf /*               (as root)
Another: sudo rm -rf /*
Fork Bomb: :(){ :|:& };:

(Fork Bombs are functions that make copies of themselves, if you accidentally run one, reboot.)

Basically, if anyone gives you a command that you are leery of, enter it into Google first, if there are articles saying "Don't run this ever!", it's probably a good idea to stop talking to whoever told you to run it :)

Now for the correct way to delete, we don't use root.  Ever! Unless you know what you are doing, Don't ever run a delete command as root!


Please type the following:

(darthlukan@SithCouncil)$ cd grammar/pronouns
(darthlukan@SithCouncil)$ rm them
(darthlukan@SithCouncil)$ ls
he  her  me  you
(darthlukan@SithCouncil)$

Well, now that we have "them" out of the way, it's time to get "you" and "her" alone!  Pay attention to the following:

(darthlukan@SithCouncil)$ rm *e
(darthlukan@SithCouncil)$ ls
her you
(darthlukan@SithCouncil)$

What the heck was that all about!?!  Now you see why "rm -rf /*" is so dangerous, especially as root.  What do you think would have happened if we would have forgotten to type "e" after the "*" (asterisk)?  Exactly what you hopefully have caught onto on your own.  Everything in the folder would have been deleted!  "*" is what we call a "wildcard".  The above command basically said "delete everything(*) with an "e" at the end of the name.  That's why even though "her" has an "e", the file was not removed.  What do you think would have happened if we would have entered in "rm h*"?  Think about it.  That's right! It would have been just "me" and "you" (which is not nearly as exciting as what we actually are left with, "you" and "her").

Go ahead and step out of the folder by typing "cd ..".  You should now be inside of the "grammar" folder.  Go ahead and type the command "rm pronouns/*".  Now type "ls pronouns".  You shouldn't see anything but space.  You just deleted files without actually needing to be in the folder.  Now, I'm going to show you two ways of deleting a folder:

(darthlukan@SithCouncil)$ rm -r pronouns
(darthlukan@SithCouncil)$ rmdir pronouns

"rm -r" means, "remove recursively" and "rmdir" means, "remove directory".  I'll leave it up to you which you prefer, both do the same thing.  Just remember to be very careful when deleting files and folders!  You can very easily cause more harm than good.  When all else fails, make a backup!!!  If you aren't sure that you've made a recent backup, make another backup!



Homework


I know that it must seem demoralizing and "wrong" to assign homework for something that should be fun, but you'll get over that pretty soon.  I want you to create a folder called "practice".  In this folder I want you to practice everything that we've talked about today as well as what we talked about last time.  I want you to make more folders and files, move them, copy them, delete them.  Here's the catch, I want you to find different ways of doing all of these things.  Play with the asterisk (*) and see what other uses it has with those commands that we've learned to see if you can make messing with files easier.  See in which ways it can cause problems.  Practice, practice, practice!


What to expect next time

Next time we'll talk about reading and writing to files using terminal commands and text editors.  Get ready! This is where you'll start to realize what kind of power (and safeguards) Linux arms you with.  It's going to be pretty exciting as we are going to look at system files and some ways to make your life easier when editing them.

See you next time!


-DarthLukan

No comments: