Some Basic Commands


There are hundreds, maybe even thousands, of commands that the Linux shell can process. But a typical power user is familiar with just a handful. These would include

  • cat Prints the contents of a file. Any text file can be viewed, with the default output being displayed on the monitor.

  • cd Change directories. When this command is used without any options, it changes from the current directory to the home directory of the user.

  • chmod Change modules (file access permissions).

    Tip

    The chmod utility can work with octal permissions such as 777 or alpha such as rwx.


  • cp Copies files and directories.

  • du Displays disk usage.

  • emacs A multi-purpose text editor (with the kitchen sink thrown in).

  • find Searches for files and can be used with many different options. For example, to find all files beginning with the three letters "ins" and list them, the command would be: find . name ins* -print.

  • gcc The GNU Compiler Collection; makes programs out of source code.

  • grep Searches for a string within input, a file, directory, or anything else specified.

    Tip

    A newer version of grep that offers a few more pattern-matching options is egrep.


  • ln Creates symbolic link (symlink) between files.

  • locate Finds files from an index.

  • ls Lists files in a directory. Options can be used with it to change the display in a great many ways, including showing hidden files (-a), in reverse order (-r), in long format (-l), and so on.

  • make Compiles and installs programs.

  • man The manual page reader that displays man pages (help files) for utilities, special files, and other entries.

  • mkdir Creates (makes) directories.

  • mv Moves files or directories.

  • ps Lists processes for the current user or all users.

  • rm Removes (deletes) files and directories.

    Note

    Of all the utilities available in Linux and there are a multitude of them one of the most dangerous is rm. In Linux, files are not merely flagged as deleted when rm is used, they are truly gone and there is not an undo feature. Be very careful when using this utility.


  • ssh The Secure Shell; connects to other machines.

  • tail Displays the last lines of a file. The opposite of this is head, which displays the first lines of a file.

  • top Shows resource usage in a constantly updated display.

  • vim A text editor.

  • which Displays the location of a command by looking through the PATH statement to find the first executable that you will encounter.

  • xargs Executes commands from its input. This is often used in conjunction with find to run commands on files once they have been found to match a specific pattern. For example, to find all files created by the user named "skipper" and look within them for the word "original", the command would be: find / -user skipper type f | xargs grep i original.

Gaining a basic understanding of what these commands do and how they can interact with each other is essential if you want to become a real wizard of the shell. This doesn't mean you have to know every option switch and types of usage, but you need to get to a situation and know what tool or tool chain is most likely to get you out of that situation.

Note

Every one of these commands (and practically all the others discussed in this book) will work in SUSE Linux, regardless of what shell you choose. Some shells have more commands built in than others, but you need not worry about dependency issues in choosing a shell.


Some of these commands are really larger applications. You learned about text editors and links in some depth in Chapter 5, "Getting Started with SUSE Linux," and about gcc and make in Chapter 28, "Using the GNU Compiler Collection and Other Programming Tools." The rest are seemingly simple instructions that reveal the shell's power when you look closely at them. That is our task here, with the aim of giving you the confidence needd to be able to mix them together to create your own commands and solve your own problems.

Displaying the Contents of a File with cat

One of the first shell commands a Unix or Linux user learns is cat, which displays the contents of a file in the shell. This is useful both because you don't have to open a text editor or similar application to see whether a certain file contains a certain string, and because you can display the results of another command as text.

The standard use of cat is to display a file like this:

cat myfile.txt 

There are two commonly used options that go with cat. You can include line numbering in cat by adding the -n switch. Adding -s displays one blank line at a time. This means if you have a file with a lot of blank lines interspersed with a few lines of text, cat will "squeeze" out all the extra blank lines, and print a line of text, a blank line (which can represent many more blank lines), more text, another blank line, more text, and so on.

You can combine these two switches as well, as in this command, that displays the output of /proc/cpuinfo, showing you information about your CPU:

cat -sn /proc/cpuinfo 

If you run this command yourself, you will see the list of items has each line numbered, and a single numbered blank line at the bottom. The file itself may have as many blank lines at the bottom as it wants; cat will only display (and count) the first one.

Finally, you can use cat to string together multiple files, and then perform operations on all of them without having to cut and paste them all together, like this:

cat -s myfile.txt muotherfile.txt 

Incidentally, some users are surprised to learn that cat does not abbreviate "catalog" or some other familiar word beginning with those three letters. cat's job is to concatenate the contents of files, as we've seen in the last example.

Making and Changing Directories with mkdir and cd

Creating new directories is a pretty simple task with mkdir. Just type the command and the name of the new directory, and if you have write permission to the new directory's parent, it will create it without a word. If you are a lazy typist, be aware that md works just as well as the more formal mkdir.

Just don't get ahead of yourself. If you want to create two directories at once, this is not always possible. While it is quite permissible to create two new directories using mkdir UserDocs Music, mkdir will complain if you try to create Music/CDs, if the Music directory does not exist already.

But wait, there's a solution to this problem. Try this command:

mkdir -p /Music/CDs 

With the -p switch, mkdir creates the parent directory, Music, then the child, CDs.

As long as we're speaking of CDs, let's switch gears and talk about changing directories. Now this cd seems like a pretty straightforward, no-frills type of command. But there are ways to maneuver quickly through your file system knowing some of cd's switches.

If you have experience with a DOS command line, you probably already know how to use .. to get to the parent directory. You may even know that cd / will take you to the Root (/) directory. What you may not know is that cd will take you to the last directory you were in before now. You also may not know that using the tilde like this: cd ~ will always take you to your home directory. Play with these until you get comfortable moving around.

Changing File Access Permissions with chmod

What you learned earlier about chmod can be greatly extended through one simple parameter: -c. This instructs chmod to display a list of all the changes it made as part of its operation, which means we can capture the output and use it for other purposes.

This switch is not a command history, but that can be a good thing. If you want a file to have certain permissions, but are not sure what the current permissions are, you can run this command. If no results display, nothing changed.

Another interesting switch is the --reference switch. Say you want all files in the current directory to have the same permissions as /home/myfile.txt, you can run this:

chmod --reference ~/myfile.txt * 

The R switch (note the capitalization) makes your command recursive through all the files and subdirectories of the current directory. If you happen to have trouble writing new files to your /home directory, run chmod R 000 /home to make all files and subdirectories read/write to their owner.

Copying, Moving, and Renaming Files with cp and mv

Managing your files and directories from the shell is pretty straightforward, and mastering the basics of cp and mv doesn't take much. But let's look at a couple of switches that will indeed help you.

To copy a file or group of files from one directory to another is simple:

cp *.txt ~/Documents 

This copies all text files from the current directory to the /home/<username>/Documents directory. All well and good, but what if there's one text file already in /Documents with the same name as one of the files you're copying? Perhaps you ought to consider more creative filename conventions, but cp's default behavior in this instance is to overwrite the existing file.

One of two switches will solve this problem for you. The i switch makes cp an interactive command, and prompts you before overwriting an existing file. Perhaps even better (at least if you know the two files are really different versions of the same file) is the u switch, which tells cp to only copy the file if it is newer than the file in the destination directory. This is also useful when synchronizing directories, say from your laptop to your desktop. Both of these switches work with mv, making it useful in both contexts.

One other thing about mv: It is the command you use to rename a file in Linux. Where you would normally include a destination path for your move operation, just type the new name. The shell will "move" the file to the new name.

Displaying Disk Usage with du

The ducommand displays the size of each file and directory that is inside the current directory. Its most basic usage is as easy as it gets:

du 

With this command, you get a long list of directories and the amount of space their files take up. Add the -a switch, and you get an even longer list, with the size of each individual file. One problem with this is that du outputs its sizes in bytes, which is excellent on the accuracy scale, but can get annoying if you have video files with tens or even hundreds of megabytes on the list. Coming to the rescue is the -h switch, making the results more human-readable, if perhaps not so precise. Big files now read as 27M (for megabyte).

Combining these two switches, along with the c switch, which gives you a total size, gives you a very nice list of files and their sizes.

du  ahc /home/mikemc 

Searching for Strings with grep

grepis one of those legendary Linux tools, a tool that genuine wizards employ with regularity. It is unquestionably a powerful tool for finding things. You use it to find text of any sort, whether in files or in standard input. Standard usage is simple:

grep  r "some text" * 

This searches through all the files in the current directory and its subdirectories for a string "some text." (The r switch makes it recursive. Note that unlike chmod, the r here is lowercase.) When grep is finished, it will display matching lines along with the name of the file the line is contained in. If you don't want to see the matching line, use the l switch. This displays all the files with text that matches, but none of the matching text.

You can also use regular expressions for your search terms (see Chapter 29, "Managing Databases," for more on regular expressions).

Here are a few more useful switches:

  • -v Inverts your search, so grep v "some text" * looks for files that do not contain the search phrase.

  • -i Changes grep's default case-sensitivity.

  • -c Delivers a count of matching lines without naming files or displaying lines. Works with v as well, to count non-matching lines.

  • -n Displays the line number of the matching line(s) in the file.

You'll see an important use for grep later when we look at piping together commands.

Finding Files from an Index with locate

The findcommand is a good tool, but it can be startlingly slow. That's where locate comes in. This is just a wonderful tool, one that speeds the process immensely. This program uses a database that indexes your directory. The key to succeeding with locate is to update this database regularly.

Note

locate is the only command in this listing not installed by default in SUSE Linux. You can install the findutils-locate package in YaST, however. When you install it, SUSE Linux will automatically update the index database nightly.


All you have to do then is run this command:

locate <filename> 

You will quickly get a list of every directory that file appears in. The only downside is that you can only search for a filename, not any other property of the file. Once you've found it, of course, you can use other commands to get more information about it if you need it.

Listing Files in the Current Directory with ls

You use ls by itself to get a plain list of files in the current (or specified) directory. You can also use all the standard wildcards to find particular files or types of files.

Listing files is a pretty straightforward process, but displaying the results can be problematic. The ls command offers many ways to display and use your results. Here are some of the standard switches for ls:

  • -a Include hidden files

  • -h Display file sizes in kilobytes (K) and megabytes (M)

  • -l Displays the "long" listing, like the Details view of a GUI file manager

  • -r Reverse order

  • -R Recursively list directories (again, uppercase like chmod, not lowercase like grep)

  • -s Shows file and directory sizes

  • --sort Sorts the listing

Reading Man Pages with man

Reading man pages themselves are a simple task, at least if you can understand the sometimes too-dense geekspeak that contribute to the notion that Linux has a steep learning curve. But leaving the language barrier aside, it can be difficult to move around in a man page, unless you know that you're in the paging program called less. This is the enhanced version of the original Unix pager, called more.

The purpose of a pager is to deal with the pesky problem of display output that takes up more than one screen in a shell. If you run cat in a standard command-line window (not an X terminal with a scroll bar), unless the file is awfully short, you will only see the last part of the file. Using less <filename> allows you to use your keyboard to scroll through the contents of a file, like a man page.

Navigating in less is mostly intuitive. The arrow keys, Page Up and Page Down, work as you would expect them to, and the space bar acts much the same as Page Down (as in a web browser). Pressing Home takes you to the top of the file, and End takes you to the bottom.

There are a few interesting ways to get around in less, though. If you want to see Line 27 of this man page, just type 27g. You can also use percentages; to move to the 87% mark of the page, type 87p. You can even do a text search by pressing the forward slash (/) and typing your search term(s). To see the next match, type / and Enter. To search backward, use the question mark (?) instead of the slash.

Finally, always remember to press q to quit your man page and return to the shell prompt.

Listing Processes with ps

There are few more powerful commands at your disposal than ps, which can tell you an extraordinary amount of things about your machine and how it runs. The tricky thing about ps is that it doesn't use a hyphen with its command switches, so you have to keep that in mind when you run it.

The purpose of ps is to give you a list of all processes attached to the current terminal, which is likely to be your PC, but could be something else if you're logged in remotely. This, in fact, makes ps a useful command when you are logged in to a remote machine. You may not know what tools you have access to, and ps will tell you. One of the standard uses for ps is to see a list of all processes for all users; use the a switch. To see all processes for all users, whether they are attached to the current terminal or not, use ps ax.

In Chapter 22, "Managing the Boot Process and Other Services," you saw the KSysGuard system monitor application display processes in a tree pattern, showing the relationships between processes. Think you can't get that in a shell? Wrong! Try ps u to get "user-oriented output."

There is a ton of options that you can use with ps to get a handle on your machine. Check out the man page for a detailed listing.

Deleting Files and Directories with rm

Way back at the beginning of the book, you were warned about rm. If you have forgotten, it bears repeating. If you are logged in as Root, and type rm rf /, you can kiss your system goodbye. While the best way to protect yourself against this eventuality is to only log in as Root (or more precisely the SuperUser) when you absolutely have to, there is a backup plan. You should implement this right away, too.

Sticky fingers at the keyboard are more of a problem than bad intentions when it comes to the problem of over-deleting. Using rm rf <directoryname> is not necessarily evil, either. All you are doing is saying "Yes, I really mean to delete this directory (and everything underneath it with the r switch), don't warn me." But if you start typing the path rm rf /home/<formeruser> and accidentally put a space after that first slash, you are indeed asking for trouble. You've gone from deleting the home directory of an old user to deleting / ...and then the old user.

The way to protect yourself is to include the --preserve-root switch every time you use rm. You aren't even required to remember this tip. Right now, just add this line to the .bashrc file in your home directory (and the .rc configuration file of any other shell you might use):

alias rm='rm --preserve-root' 

Now you don't have to think about it again. Each time you run rm, it will know not to ever delete the / directory.

Displaying the Last Lines of a File with tail

Are you seeing something funky going on with your machine? Do you want to check a log file to see what might be up? You can do this by reading active log files with tail. This command displays the last few lines of a file and updates as new lines are added. To have tail monitor your system log's security messages, try this:

tail  f /var/log/secure 

The f switch has tail "follow" the progress of the file, and deliver each new message as it is generated. To keep it running as long as the log generates messages, add the PID number (which you can get from ps) of the log you're following and add it to the command thusly:

tail  f ---pid<PID#> /var/log/secure 

Now see what's going on!

Displaying Resource Usage with top

This is another way to get a handle on what's happening on your system. More precisely, it seeks to identify the biggest resource hogs at a given moment, so if your system has slowed to a crawl, you can determine and terminate whatever process is killing your system.

You are best off running top as the SuperUser, because you never know who owns the bad-acting process. You don't actually need any switches to get top running properly. After you type top at the prompt, it will open and display a list of processes sorted with the most CPU-intensive tasks at the top. Unfortunately, those processes don't have names in the top display.

To kill the process at the top of the list, type k and enter the PID. You are prompted for a signal number (the manner in which you want the process killed), with 15 as the default. This signals the process politely, asking it to shut down. Those apps that are not wildly out of control comply with the request. If your unruly process doesn't terminate, repeat the process, only this time send the not-so-polite Signal 9 (terminate and terminate NOW).

Displaying the Location of a Command with which

One last quickie: Do you want to know the physical location of a command or application? Type which mkdir, and you'll discover that the mkdir command sits in /bin/mkdir. How useful.



SUSE Linux 10 Unleashed
SUSE Linux 10.0 Unleashed
ISBN: 0672327260
EAN: 2147483647
Year: 2003
Pages: 332

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net