Transcript
Page 1: Lpi Part 1 Linux Fundamentals

LPI certification 101 (release 2) examprep, Part 1

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Table of ContentsIf you're viewing this document online, you can click any of the topics below to link directly to that section.

1. Before you start......................................................... 22. Introducing bash........................................................ 33. Using Linux commands ............................................... 74. Creating links and removing files .................................... 135. Using wildcards......................................................... 186. Summary and resources .............................................. 21

LPI certification 101 (release 2) exam prep, Part 1 Page 1 of 22

Page 2: Lpi Part 1 Linux Fundamentals

Section 1. Before you start

About this tutorialWelcome to "Linux fundamentals," the first of four tutorials designed to prepare you for theLinux Professional Institute's 101 exam. In this tutorial, we'll introduce you to bash (thestandard Linux shell), show you how to take full advantage of standard Linux commands likels, cp, and mv, explain inodes and hard and symbolic links, and much more. By the end ofthis tutorial, you'll have a solid grounding in Linux fundamentals and will even be ready tobegin learning some basic Linux system administration tasks. By the end of this series oftutorials (eight in all), you'll have the knowledge you need to become a Linux SystemsAdministrator and will be ready to attain an LPIC Level 1 certification from the LinuxProfessional Institute if you so choose.

This particular tutorial (Part 1) is ideal for those who are new to Linux, or those who want toreview or improve their understanding of fundamental Linux concepts like copying andmoving files, creating symbolic and hard links, and using Linux's standard text-processingcommands along with pipelines and redirection. Along the way, we'll share plenty of hints,tips, and tricks to keep the tutorial "meaty" and practical, even for those with a good amountof previous Linux experience. For beginners, much of this material will be new, but moreexperienced Linux users may find this tutorial to be a great way of "rounding out" theirfundamental Linux skills.

For those who have taken the release 1 version of this tutorial for reasons other than LPIexam preparation, you probably don't need to take this one. However, if you do plan to takethe exams, you should strongly consider reading this revised tutorial.

About the authorResiding in Albuquerque, New Mexico, Daniel Robbins is the Chief Architect of Gentoo Linuxan advanced ports-based Linux metadistribution. He also writes articles, tutorials, and tips forthe IBM developerWorks Linux zone and Intel Developer Services and has also served as acontributing author for several books, including Samba Unleashed and SuSE LinuxUnleashed. Daniel enjoys spending time with his wife, Mary, and his daughter, Hadassah.You can contact Daniel at [email protected].

For technical questions about the content of this tutorial, contact the author, Daniel Robbins,at [email protected].

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 2 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 3: Lpi Part 1 Linux Fundamentals

Section 2. Introducing bash

The shellIf you've used a Linux system, you know that when you log in, you are greeted by a promptthat looks something like this:

$

The particular prompt that you see may look quite different. It may contain your system'shostname, the name of the current working directory, or both. But regardless of what yourprompt looks like, there's one thing that's certain. The program that printed that prompt iscalled a "shell," and it's very likely that your particular shell is a program called bash.

Are you running bash?You can check to see if you're running bash by typing:

$ echo $SHELL/bin/bash

If the above line gave you an error or didn't respond similarly to our example, then you maybe running a shell other than bash. In that case, most of this tutorial should still apply, but itwould be advantageous for you to switch to bash for the sake of preparing for the 101 exam.(The next tutorial in this series, on basic administration, covers changing your shell using thechsh command.)

About bashBash, an acronym for "Bourne-again shell," is the default shell on most Linux systems. Theshell's job is to obey your commands so that you can interact with your Linux system. Whenyou're finished entering commands, you may instruct the shell to exit or logout, at whichpoint you'll be returned to a login prompt.

By the way, you can also log out by pressing control-D at the bash prompt.

Using "cd"As you've probably found, staring at your bash prompt isn't the most exciting thing in theworld. So, let's start using bash to navigate around our filesystem. At the prompt, type thefollowing (without the $):

$ cd /

We've just told bash that you want to work in /, also known as the root directory; all thedirectories on the system form a tree, and / is considered the top of this tree, or the root. cdsets the directory where you are currently working, also known as the "current working

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 3 of 22

Page 4: Lpi Part 1 Linux Fundamentals

directory".

PathsTo see bash's current working directory, you can type:

$ pwd/

In the above example, the / argument to cd is called a path. It tells cd where we want to go.In particular, the / argument is an absolute path, meaning that it specifies a location relativeto the root of the filesystem tree.

Absolute pathsHere are some other absolute paths:

/dev/usr/usr/bin/usr/local/bin

As you can see, the one thing that all absolute paths have in common is that they begin with/. With a path of /usr/local/bin, we're telling cd to enter the / directory, then the usr directoryunder that, and then local and bin. Absolute paths are always evaluated by starting at / first.

Relative pathsThe other kind of path is called a relative path. Bash, cd, and other commands alwaysinterpret these paths relative to the current directory. Relative paths never begin with a /. So,if we're in /usr:

$ cd /usr

Then, we can use a relative path to change to the /usr/local/bin directory:

$ cd local/bin$ pwd/usr/local/bin

Using ..Relative paths may also contain one or more .. directories. The .. directory is a specialdirectory that points to the parent directory. So, continuing from the example above:

$ pwd

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 4 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 5: Lpi Part 1 Linux Fundamentals

/usr/local/bin$ cd ..$ pwd/usr/local

As you can see, our current directory is now /usr/local. We were able to go "backwards" onedirectory, relative to the current directory that we were in.

Using .., continuedIn addition, we can also add .. to an existing relative path, allowing us to go into a directorythat's alongside one we are already in, for example:

$ pwd/usr/local$ cd ../share$ pwd/usr/share

Relative path examplesRelative paths can get quite complex. Here are a few examples, all without the resultanttarget directory displayed. Try to figure out where you'll end up after typing these commands:

$ cd /bin$ cd ../usr/share/zoneinfo

$ cd /usr/X11R6/bin$ cd ../lib/X11

$ cd /usr/bin$ cd ../bin/../bin

Now, try them out and see if you got them right :)

Understanding .Before we finish our coverage of cd, there are a few more things I need to mention. First,there is another special directory called ., which means "the current directory". While thisdirectory isn't used with the cd command, it's often used to execute some program in thecurrent directory, as follows:

$ ./myprog

In the above example, the myprog executable residing in the current working directory willbe executed.

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 5 of 22

Page 6: Lpi Part 1 Linux Fundamentals

cd and the home directoryIf we wanted to change to our home directory, we could type:

$ cd

With no arguments, cd will change to your home directory, which is /root for the superuserand typically /home/username for a regular user. But what if we want to specify a file in ourhome directory? Maybe we want to pass a file argument to the myprog command. If the filelives in our home directory, we can type:

$ ./myprog /home/drobbins/myfile.txt

However, using an absolute path like that isn't always convenient. Thankfully, we can use the~ (tilde) character to do the same thing:

$ ./myprog ~/myfile.txt

Other users' home directoriesBash will expand a lone ~ to point to your home directory, but you can also use it to point toother users' home directories. For example, if we wanted to refer to a file called fredsfile.txt inFred's home directory, we could type:

$ ./myprog ~fred/fredsfile.txt

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 6 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 7: Lpi Part 1 Linux Fundamentals

Section 3. Using Linux commands

Introducing lsNow, we'll take a quick look at the ls command. Very likely, you're already familiar with lsand know that typing it by itself will list the contents of the current working directory:

$ cd /usr$ lsX11R6 doc i686-pc-linux-gnu lib man sbin sslbin gentoo-x86 include libexec portage share tmpdistfiles i686-linux info local portage.old src

By specifying the -a option, you can see all of the files in a directory, including hidden files:those that begin with .. As you can see in the following example, ls -a reveals the . and.. special directory links:

$ ls -a. bin gentoo-x86 include libexec portage share tmp.. distfiles i686-linux info local portage.old srcX11R6 doc i686-pc-linux-gnu lib man sbin ssl

Long directory listingsYou can also specify one or more files or directories on the ls command line. If you specify afile, ls will show that file only. If you specify a directory, ls will show the contents of thedirectory. The -l option comes in very handy when you need to view permissions,ownership, modification time, and size information in your directory listing.

Long directory listings, continuedIn the following example, we use the -l option to display a full listing of my /usr directory.

$ ls -l /usrdrwxr-xr-x 7 root root 168 Nov 24 14:02 X11R6drwxr-xr-x 2 root root 14576 Dec 27 08:56 bindrwxr-xr-x 2 root root 8856 Dec 26 12:47 distfileslrwxrwxrwx 1 root root 9 Dec 22 20:57 doc -> share/docdrwxr-xr-x 62 root root 1856 Dec 27 15:54 gentoo-x86drwxr-xr-x 4 root root 152 Dec 12 23:10 i686-linuxdrwxr-xr-x 4 root root 96 Nov 24 13:17 i686-pc-linux-gnudrwxr-xr-x 54 root root 5992 Dec 24 22:30 includelrwxrwxrwx 1 root root 10 Dec 22 20:57 info -> share/infodrwxr-xr-x 28 root root 13552 Dec 26 00:31 libdrwxr-xr-x 3 root root 72 Nov 25 00:34 libexecdrwxr-xr-x 8 root root 240 Dec 22 20:57 locallrwxrwxrwx 1 root root 9 Dec 22 20:57 man -> share/manlrwxrwxrwx 1 root root 11 Dec 8 07:59 portage -> gentoo-x86/drwxr-xr-x 60 root root 1864 Dec 8 07:55 portage.olddrwxr-xr-x 3 root root 3096 Dec 22 20:57 sbindrwxr-xr-x 46 root root 1144 Dec 24 15:32 sharedrwxr-xr-x 8 root root 328 Dec 26 00:07 src

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 7 of 22

Page 8: Lpi Part 1 Linux Fundamentals

drwxr-xr-x 6 root root 176 Nov 24 14:25 ssllrwxrwxrwx 1 root root 10 Dec 22 20:57 tmp -> ../var/tmp

The first column displays permissions information for each item in the listing. I'll explain howto interpret this information in a bit. The next column lists the number of links to eachfilesystem object, which we'll gloss over now but return to later. The third and fourth columnslist the owner and group, respectively. The fifth column lists the object size. The sixth columnis the "last modified" time or "mtime" of the object. The last column is the object's name. Ifthe file is a symbolic link, you'll see a trailing -> and the path to which the symbolic linkpoints.

Looking at directoriesSometimes, you'll want to look at a directory, rather than inside it. For these situations, youcan specify the -d option, which will tell ls to look at any directories that it would normallylook inside:

$ ls -dl /usr /usr/bin /usr/X11R6/bin ../sharedrwxr-xr-x 4 root root 96 Dec 18 18:17 ../sharedrwxr-xr-x 17 root root 576 Dec 24 09:03 /usrdrwxr-xr-x 2 root root 3192 Dec 26 12:52 /usr/X11R6/bindrwxr-xr-x 2 root root 14576 Dec 27 08:56 /usr/bin

Recursive and inode listingsSo you can use -d to look at a directory, but you can also use -R to do the opposite: not justlook inside a directory, but recursively look inside all the files and directories inside thatdirectory! We won't include any example output for this option (since it's generallyvoluminous), but you may want to try a few ls -R and ls -Rl commands to get a feel forhow this works.

Finally, the -i ls option can be used to display the inode numbers of the filesystem objects inthe listing:

$ ls -i /usr1409 X11R6 314258 i686-linux 43090 libexec 13394 sbin1417 bin 1513 i686-pc-linux-gnu 5120 local 13408 share8316 distfiles 1517 include 776 man 23779 src43 doc 1386 info 93892 portage 36737 ssl

70744 gentoo-x86 1585 lib 5132 portage.old 784 tmp

Understanding inodes, Part 1Every object on a filesystem is assigned a unique index, called an inode number. This mightseem trivial, but understanding inodes is essential to understanding many filesystemoperations. For example, consider the . and .. links that appear in every directory. To fullyunderstand what a .. directory actually is, we'll first take a look at /usr/local's inode number:

$ ls -id /usr/local

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 8 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 9: Lpi Part 1 Linux Fundamentals

5120 /usr/local

The /usr/local directory has an inode number of 5120. Now, let's take a look at the inodenumber of /usr/local/bin/..:

$ ls -id /usr/local/bin/..5120 /usr/local/bin/..

Understanding inodes, Part 2As you can see, /usr/local/bin/.. has the same inode number as /usr/local! Here's how can wecome to grips with this shocking revelation. In the past, we've considered /usr/local to be thedirectory itself. Now, we discover that inode 5120 is in fact the directory, and we have foundtwo directory entries (called "links") that point to this inode. Both /usr/local and /usr/local/bin/..are links to inode 5120. Although inode 5120 only exists in one place on disk, multiple thingslink to it. Inode 5120 is the actual entry on disk.

Understanding inodes, Part 3In fact, we can see the total number of times that inode 5120 is referenced by using the ls-dl command:

$ ls -dl /usr/localdrwxr-xr-x 8 root root 240 Dec 22 20:57 /usr/local

If we take a look at the second column from the left, we see that the directory /usr/local(inode 5120) is referenced eight times. On my system, here are the various paths thatreference this inode:

/usr/local/usr/local/./usr/local/bin/../usr/local/games/../usr/local/lib/../usr/local/sbin/../usr/local/share/../usr/local/src/..

mkdirLet's take a quick look at the mkdir command, which can be used to create new directories.The following example creates three new directories, tic, tac, and toe, all under /tmp:

$ cd /tmp$ mkdir tic tac toe

By default, the mkdir command doesn't create parent directories for you; the entire path upto the next-to-last element needs to exist. So, if you want to create the directorieswon/der/ful, you'd need to issue three separate mkdir commands:

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 9 of 22

Page 10: Lpi Part 1 Linux Fundamentals

$ mkdir won/der/fulmkdir: cannot create directory `won/der/ful': No such file or directory$ mkdir won$ mkdir won/der$ mkdir won/der/ful

mkdir -pHowever, mkdir has a handy -p option that tells mkdir to create any missing parentdirectories, as you can see here:

$ mkdir -p easy/as/pie

All in all, pretty straightforward. To learn more about the mkdir command, type man mkdirto read the manual page. This will work for nearly all commands covered here (for example,man ls), except for cd, which is built-in to bash.

touchNow, we're going to take a quick look at the cp and mv commands, used to copy, rename,and move files and directories. To begin this overview, we'll first use the touch command tocreate a file in /tmp:

$ cd /tmp$ touch copyme

The touch command updates the "mtime" of a file if it exists (recall the sixth column in ls-l output). If the file doesn't exist, then a new, empty file will be created. You should nowhave a /tmp/copyme file with a size of zero.

echoNow that the file exists, let's add some data to the file. We can do this using the echocommand, which takes its arguments and prints them to standard output. First, the echocommand by itself:

$ echo "firstfile"firstfile

echo and redirectionNow, the same echo command with output redirection:

$ echo "firstfile" > copyme

The greater-than sign tells the shell to write echo's output to a file called copyme. This file

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 10 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 11: Lpi Part 1 Linux Fundamentals

will be created if it doesn't exist, and will be overwritten if it does exist. By typing ls -l, wecan see that the copyme file is 10 bytes long, since it contains the word firstfile and thenewline character:

$ ls -l copyme-rw-r--r-- 1 root root 10 Dec 28 14:13 copyme

cat and cpTo display the contents of the file on the terminal, use the cat command:

$ cat copymefirstfile

Now, we can use a basic invocation of the cp command to create a copiedme file from theoriginal copyme file:

$ cp copyme copiedme

Upon investigation, we find that they are truly separate files; their inode numbers aredifferent:

$ ls -i copyme copiedme648284 copiedme 650704 copyme

mvNow, let's use the mv command to rename "copiedme" to "movedme". The inode number willremain the same; however, the filename that points to the inode will change.

$ mv copiedme movedme$ ls -i movedme648284 movedme

A moved file's inode number will remain the same as long as the destination file resides onthe same filesystem as the source file. We'll take a closer look at filesystems in Part 3 of thistutorial series.

While we're talking about mv, let's look at another way to use this command. mv, in additionto allowing us to rename files, also allows us to move one or more files to another location inthe directory heirarchy. For example, to move /var/tmp/myfile.txt to /home/drobbins (whichhappens to be my home directory,) I could type:

$ mv /var/tmp/myfile.txt /home/drobbins

After typing this command, myfile.txt will be moved to /home/drobbins/myfile.txt. And if/home/drobbins is on a different filesystem than /var/tmp, the mv command will handle thecopying of myfile.txt to the new filesystem and erasing it from the old filesystem. As you

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 11 of 22

Page 12: Lpi Part 1 Linux Fundamentals

might guess, when myfile.txt is moved between filesystems, the myfile.txt at the new locationwill have a new inode number. This is because every filesystem has its own independent setof inode numbers.

We can also use the mv command to move multiple files to a single destination directory. Forexample, to move myfile1.txt and myarticle3.txt to /home/drobbins, I could type:

$ mv /var/tmp/myfile1.txt /var/tmp/myarticle3.txt /home/drobbins

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 12 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 13: Lpi Part 1 Linux Fundamentals

Section 4. Creating links and removing files

Hard linksWe've mentioned the term "link" when referring to the relationship between directory entries(the "names" we type) and inodes (the index numbers on the underlying filesystem that wecan usually ignore.) There are actually two kinds of links available on Linux. The kind we'vediscussed so far are called hard links. A given inode can have any number of hard links, andthe inode will persist on the filesystem until the all the hard links disappear. When the lasthard link disappears and no program is holding the file open, Linux will delete the fileautomatically. New hard links can be created using the ln command:

$ cd /tmp$ touch firstlink$ ln firstlink secondlink$ ls -i firstlink secondlink15782 firstlink 15782 secondlink

Hard links, continuedAs you can see, hard links work on the inode level to point to a particular file. On Linuxsystems, hard links have several limitations. For one, you can only make hard links to files,not directories. That's right; even though . and .. are system-created hard links to directories,you (even as the "root" user) aren't allowed to create any of your own. The second limitationof hard links is that they can't span filesystems. This means that you can't create a link from/usr/bin/bash to /bin/bash if your / and /usr directories exist on separate filesystems.

Symbolic linksIn practice, symbolic links (or symlinks) are used more often than hard links. Symlinks are aspecial file type where the link refers to another file by name, rather than directly to the inode.Symlinks do not prevent a file from being deleted; if the target file disappears, then thesymlink will just be unusable, or broken.

Symbolic links, continuedA symbolic link can be created by passing the -s option to ln.

$ ln -s secondlink thirdlink$ ls -l firstlink secondlink thirdlink-rw-rw-r-- 2 agriffis agriffis 0 Dec 31 19:08 firstlink-rw-rw-r-- 2 agriffis agriffis 0 Dec 31 19:08 secondlinklrwxrwxrwx 1 agriffis agriffis 10 Dec 31 19:39 thirdlink -> secondlink

Symbolic links can be distinguished in ls -l output from normal files in three ways. First,notice that the first column contains an l character to signify the symbolic link. Second, thesize of the symbolic link is the number of characters in the target (secondlink, in thiscase). Third, the last column of the output displays the target filename preceded by a cutelittle ->.

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 13 of 22

Page 14: Lpi Part 1 Linux Fundamentals

Symlinks in-depth, part 1Symbolic links are generally more flexible than hard links. You can create a symbolic link toany type of filesystem object, including directories. And because the implementation ofsymbolic links is based on paths (not inodes), it's perfectly fine to create a symbolic link thatpoints to an object on another physical filesystem. However, this fact can also make symboliclinks tricky to understand.

Symlinks in-depth, part 2Consider a situation where we want to create a link in /tmp that points to /usr/local/bin.Should we type this:

$ ln -s /usr/local/bin bin1$ ls -l bin1lrwxrwxrwx 1 root root 14 Jan 1 15:42 bin1 -> /usr/local/bin

Or alternatively:

$ ln -s ../usr/local/bin bin2$ ls -l bin2lrwxrwxrwx 1 root root 16 Jan 1 15:43 bin2 -> ../usr/local/bin

Symlinks in-depth, part 3As you can see, both symbolic links point to the same directory. However, if our secondsymbolic link is ever moved to another directory, it will be "broken" because of the relativepath:

$ ls -l bin2lrwxrwxrwx 1 root root 16 Jan 1 15:43 bin2 -> ../usr/local/bin$ mkdir mynewdir$ mv bin2 mynewdir$ cd mynewdir$ cd bin2bash: cd: bin2: No such file or directory

Because the directory /tmp/usr/local/bin doesn't exist, we can no longer change directoriesinto bin2; in other words, bin2 is now broken.

Symlinks in-depth, part 4For this reason, it is sometimes a good idea to avoid creating symbolic links with relative pathinformation. However, there are many cases where relative symbolic links come in handy.Consider an example where you want to create an alternate name for a program in /usr/bin:

# ls -l /usr/bin/keychain

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 14 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 15: Lpi Part 1 Linux Fundamentals

-rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/bin/keychain

Symlinks in-depth, part 5As the root user, you may want to create an alternate name for "keychain," such as "kc". Inthis example, we have root access, as evidenced by our bash prompt changing to "#". Weneed root access because normal users aren't able to create files in /usr/bin. As root, wecould create an alternate name for keychain as follows:

# cd /usr/bin# ln -s /usr/bin/keychain kc# ls -l keychain-rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/bin/keychain# ls -l kclrwxrwxrwx 1 root root 17 Mar 27 17:44 kc -> /usr/bin/keychain

In this example, we created a symbolic link called kc that points to the file /usr/bin/keychain.

Symlinks in-depth, part 6While this solution will work, it will create problems if we decide that we want to move bothfiles, /usr/bin/keychain and /usr/bin/kc to /usr/local/bin:

# mv /usr/bin/keychain /usr/bin/kc /usr/local/bin# ls -l /usr/local/bin/keychain-rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/local/bin/keychain# ls -l /usr/local/bin/kclrwxrwxrwx 1 root root 17 Mar 27 17:44 kc -> /usr/bin/keychain

Because we used an absolute path in our symbolic link, our kc symlink is still pointing to/usr/bin/keychain, which no longer exists since we moved /usr/bin/keychain to /usr/local/bin.

That means that kc is now a broken symlink. Both relative and absolute paths in symboliclinks have their merits, and you should use a type of path that's appropriate for yourparticular application. Often, either a relative or absolute path will work just fine. Thefollowing example would have worked even after both files were moved:

# cd /usr/bin# ln -s keychain kc# ls -l kclrwxrwxrwx 1 root root 8 Jan 5 12:40 kc -> keychain# mv keychain kc /usr/local/bin# ls -l /usr/local/bin/keychain-rwxr-xr-x 1 root root 10150 Dec 12 20:09 /usr/local/bin/keychain# ls -l /usr/local/bin/kclrwxrwxrwx 1 root root 17 Mar 27 17:44 kc -> keychain

Now, we can run the keychain program by typing /usr/local/bin/kc./usr/local/bin/kc points to the program keychain in the same directory as kc.

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 15 of 22

Page 16: Lpi Part 1 Linux Fundamentals

rmNow that we know how to use cp, mv, and ln, it's time to learn how to remove objects fromthe filesystem. Normally, this is done with the rm command. To remove files, simply specifythem on the command line:

$ cd /tmp$ touch file1 file2$ ls -l file1 file2-rw-r--r-- 1 root root 0 Jan 1 16:41 file1-rw-r--r-- 1 root root 0 Jan 1 16:41 file2$ rm file1 file2$ ls -l file1 file2ls: file1: No such file or directoryls: file2: No such file or directory

Note that under Linux, once a file is rm'd, it's typically gone forever. For this reason, manyjunior system administrators will use the -i option when removing files. The -i option tellsrm to remove all files in interactive mode -- that is, prompt before removing any file. Forexample:

$ rm -i file1 file2rm: remove regular empty file `file1'? yrm: remove regular empty file `file2'? y

In the above example, the rm command prompted whether or not the specified files should*really* be deleted. In order for them to be deleted, I had to type "y" and Enter twice. If I hadtyped "n", the file would not have been removed. Or, if I had done something really wrong, Icould have typed Control-C to abort the rm -i command entirely -- all before it is able to doany potential damage to my system.

If you are still getting used to the rm command, it can be useful to add the following line toyour ~/.bashrc file using your favorite text editor, and then log out and log back in. Then, anytime you type rm, the bash shell will convert it automatically to an rm -i command. Thatway, rm will always work in interactive mode:

alias rm="rm -i"

rmdirTo remove directories, you have two options. You can remove all the objects inside thedirectory and then use rmdir to remove the directory itself:

$ mkdir mydir$ touch mydir/file1$ rm mydir/file1$ rmdir mydir

This method is commonly referred to as "directory removal for suckers." All real power usersand administrators worth their salt use the much more convenient rm -rf command,covered next.

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 16 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 17: Lpi Part 1 Linux Fundamentals

rm and directoriesThe best way to remove a directory is to use the recursive force options of the rm commandto tell rm to remove the directory you specify, as well as all objects contained in the directory:

$ rm -rf mydir

Generally, rm -rf is the preferred method of removing a directory tree. Be very carefulwhen using rm -rf, since its power can be used for both good and evil :)

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 17 of 22

Page 18: Lpi Part 1 Linux Fundamentals

Section 5. Using wildcards

Introducing wildcardsIn your day-to-day Linux use, there are many times when you may need to perform a singleoperation (such as rm) on many filesystem objects at once. In these situations, it can oftenbe cumbersome to type in many files on the command line:

$ rm file1 file2 file3 file4 file5 file6 file7 file8

Introducing wildcards, continuedTo solve this problem, you can take advantage of Linux's built-in wildcard support. Thissupport, also called "globbing" (for historical reasons), allows you to specify multiple files atonce by using a wildcard pattern. Bash and other Linux commands will interpret this patternby looking on disk and finding any files that match it. So, if you had files file1 through file8 inthe current working directory, you could remove these files by typing:

$ rm file[1-8]

Or if you simply wanted to remove all files whose names begin with file as well as any filenamed file, you could type:

$ rm file*

The * wildcard matches any character or sequence of characters, or even "no character." Ofcourse, glob wildcards can be used for more than simply removing files, as we'll see in thenext panel.

Understanding non-matchesIf you wanted to list all the filesystem objects in /etc beginning with g as well as any file calledg, you could type:

$ ls -d /etc/g*/etc/gconf /etc/ggi /etc/gimp /etc/gnome /etc/gnome-vfs-mime-magic /etc/gpm /etc/group /etc/group-

Now, what happens if you specify a pattern that doesn't match any filesystem objects? In thefollowing example, we try to list all the files in /usr/bin that begin with asdf and end with jkl,including potentially the file asdfjkl:

$ ls -d /usr/bin/asdf*jklls: /usr/bin/asdf*jkl: No such file or directory

Understanding non-matches, continued

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 18 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 19: Lpi Part 1 Linux Fundamentals

Here's what happened. Normally, when we specify a pattern, that pattern matches one ormore files on the underlying filesystem, and bash replaces the pattern with aspace-separated list of all matching objects . However, when the pattern doesn't produce anymatches, bash leaves the argument, wildcards and all, as-is. So, then ls can't find the file/usr/bin/asdf*jkl and it gives us an error. The operative rule here is that glob patterns areexpanded only if they match objects in the filesystem. Otherwise they remain as is and arepassed literally to the program you're calling.

Wildcard syntax: *Now that we've seen how globbing works, we should look at wildcard syntax. You can usespecial characters for wildcard expansion:

* will match zero or more characters. It means "anything can go here, including nothing".Examples:

• /etc/g* matches all files in /etc that begin with g, or a file called g.

• /tmp/my*1 matches all files in /tmp that begin with my and end with 1, including the filemy1.

Wildcard syntax: ?? matches any single character. Examples:

• myfile? matches any file whose name consists of myfile followed by a singlecharacter.

• /tmp/notes?txt would match both /tmp/notes.txt and /tmp/notes_txt, if theyexist.

Wildcard syntax: []This wildcard is like a ?, but it allows more specificity. To use this wildcard, place anycharacters you'd like to match inside the []. The resultant expression will match a singleoccurrence of any of these characters. You can also use - to specify a range, and evencombine ranges. Examples:

• myfile[12] will match myfile1 and myfile2. The wildcard will be expanded as longas at least one of these files exists in the current directory.

• [Cc]hange[Ll]og will match Changelog, ChangeLog, changeLog, and changelog.As you can see, using bracket wildcards can be useful for matching variations incapitalization.

• ls /etc/[0-9]* will list all files in /etc that begin with a number.

• ls /tmp/[A-Za-z]* will list all files in /tmp that begin with an upper or lower-case letter.

Wildcard syntax: [!]

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 19 of 22

Page 20: Lpi Part 1 Linux Fundamentals

The [!] construct is similar to the [] construct, except rather than matching any charactersinside the brackets, it'll match any character, as long as it is not listed between the [! and ].Example:

• rm myfile[!9] will remove all files named myfile plus a single character, except formyfile9.

Wildcard caveatsHere are some caveats to watch out for when using wildcards. Since bash treatswildcard-related characters (?, [, ], and *) specially, you need to take special care whentyping in an argument to a command that contains these characters. For example, if youwant to create a file that contains the string [fo]*, the following command may not do whatyou want:

$ echo [fo]* > /tmp/mynewfile.txt

If the pattern [fo]* matches any files in the current working directory, then you'll find thenames of those files inside /tmp/mynewfile.txt rather than a literal [fo]* like you wereexpecting. The solution? Well, one approach is to surround your characters with singlequotes, which tell bash to perform absolutely no wildcard expansion on them:

$ echo '[fo]*' > /tmp/mynewfile.txt

Wildcard caveats, continuedUsing this approach, your new file will contain a literal [fo]* as expected. Alternatively, youcould use backslash escaping to tell bash that [, ], and * should be treated literally ratherthan as wildcards:

$ echo \[fo\]\* > /tmp/mynewfile.txt

Both approaches (single quotes and backslash escaping) have the same effect. Since we'retalking about backslash expansion, now would be a good time to mention that in order tospecify a literal \, you can either enclose it in single quotes as well, or type \\ instead (it willbe expanded to \).

Single vs. double quotesNote that double quotes will work similarly to single quotes, but will still allow bash to dosome limited expansion. Therefore, single quotes are your best bet when you are trulyinterested in passing literal text to a command. For more information on wildcard expansion,type man 7 glob. For more information on quoting in bash, type man 8 glob and read thesection titled QUOTING. If you're planning to take the LPI exams, consider this a homeworkassignment :)

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 20 of 22 LPI certification 101 (release 2) exam prep, Part 1

Page 21: Lpi Part 1 Linux Fundamentals

Section 6. Summary and resources

SummaryCongratulations; you've reached the end of our review of Linux fundamentals! I hope that ithas helped you to firm up your foundational Linux knowledge. The topics you've learnedhere, including the basics of bash, basic Linux commands, links, and wildcards, have laid thegroundwork for our next tutorial on basic administration, in which we'll cover topics likeregular expressions, ownership and permissions, user account management, and more.

By continuing in this tutorial series, you'll soon be ready to attain your LPIC Level 1Certification from the Linux Professional Institute. Speaking of LPIC certification, if this issomething you're interested in, then we recommend that you study the Resources in the nextpanel, which have been carefully selected to augment the material covered in this tutorial.

ResourcesIn the "Bash by example" article series on developerWorks, Daniel shows you how to usebash programming constructs to write your own bash scripts. This series (particularly Parts1 and 2) will be good preparation for the LPIC Level 1 exam:

• Bash by example, Part 1: Fundamental programming in the Bourne-again shell

• Bash by example, Part 2: More bash programming fundamentals

• Bash by example, Part 3: Exploring the ebuild system

If you're a beginning or intermediate Linux user, you really owe it to yourself to check out theTechnical FAQ for Linux users, a 50-page in-depth list of frequently-asked Linux questions,along with detailed answers. The FAQ itself is in PDF (Acrobat) format.

If you're not too familiar with the vi editor, see the developerWorks tutorial Intro to vi. Thistutorial gives you a gentle yet fast-paced introduction to this powerful text editor. Considerthis must-read material if you don't know how to use vi.

Your feedbackPlease let us know whether this tutorial was helpful to you and how we could make it better.We'd also like to hear about other topics you'd like to see covered in developerWorkstutorials.

For questions about the content of this tutorial, contact the author, Daniel Robbins, [email protected].

Colophon

This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorialgenerator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLT

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

LPI certification 101 (release 2) exam prep, Part 1 Page 21 of 22

Page 22: Lpi Part 1 Linux Fundamentals

extension functions that convert an XML file into a number of HTML pages, a zip file, JPEGheading graphics, and two PDF files. Our ability to generate multiple text and binary formatsfrom a single source file illustrates the power and flexibility of XML. (It also saves ourproduction team a great deal of time and effort.)

You can get the source code for the Toot-O-Matic atwww6.software.ibm.com/dl/devworks/dw-tootomatic-p. The tutorial Building tutorials with theToot-O-Matic demonstrates how to use the Toot-O-Matic to create your own tutorials.developerWorks also hosts a forum devoted to the Toot-O-Matic; it's available atwww-105.ibm.com/developerworks/xml_df.nsf/AllViewTemplate?OpenForm&RestrictToCategory=11.We'd love to know what you think about the tool.

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 22 of 22 LPI certification 101 (release 2) exam prep, Part 1