Learning the shell

From SHellium Wiki
Jump to: navigation, search
Geographylogo.png In other languages: English | Afrikaans | Albanian | Arabic | Brazilian | Bulgarian | Catalan | Chinese | Croatian | Czech | Danish | Dutch | Esperanto | Estonian | Filipino | Finnish | Flemish | French | German | Greek | Hebrew | Hindi | Hungarian | Indonesian | Italian | Japanese | Latvian | Lithuanian | Macedonian | Malay | Malayalam | Norwegian (Bokmål) | Norwegian (Nynorsk) | Persian | Polish | Portuguese | Romanian | Russian | Serbian | Slovak | Slovenian | Spanish | Swedish | Turkish | Ukrainian | Urdu

Contents

Navigation

In this lesson, I will introduce your first three commands: pwd (print working directory), cd (change directory), and ls (list files and directories).

If you have not worked with a command line interface before, you will need to pay close attention to this lesson, since the concepts will take some getting used to.

File System Organization

Like other operating systems, the files on a Linux system are arranged in what is called a hierarchical directory structure. This means that they are organized in a tree-like pattern of directories (called folders in other systems), which may contain files and other directories. The first directory in the file system is called the root directory. The root directory contains files and subdirectories, which contain more files and subdirectories and so on and so on.

Most graphical environments today include a file manager program to view and manipulate the contents of the file system. Often you will see the file system represented by a tree like this:

[-]- /
     |
    [+]- bin
     |
    [+]- boot
     |
    [+]- dev
     |
    [+]- etc
     |
    [-]- home
     |   |
     |  [-]- Documents
     |       |
     |      [+]- Pictures
     |       |
     |      [+]- vacation
     |
    [+]- lib

One important difference between other operating systems and Unix/Linux is that Linux does not employ the concept of drive letters. While drive letters split the file system into a series of different trees (one for each drive), Linux always has a single tree. Different storage devices may contain different branches of the tree, but there is always a single tree.

pwd

Since a command line interface cannot provide graphic pictures of the file system structure, it must have a different way of representing it. Think of the file system tree as a maze, and you are standing in it. At any given moment, you stand in a single directory. Inside that directory, you can see its files and the pathway to its parent directory and the pathways to the subdirectories of the directory in which you are standing.

The directory you are standing in is called the working directory. To find the name of the working directory, use the pwd command.

[me@shellium me]$ pwd
/home/me

When you first log on to a Linux system, the working directory is set to your home directory. This is where you put your files. On most systems, your home directory will be called /home/your_user_name, but it could be anything according to the whims of the system administrator.

To list the files in the working directory, use the ls command.

[me@shellium me]$ ls
bin         logs        public_html        somefile.log
[me@shellium me]$_

We will come back to ls in the next lesson. There are a lot of fun things you can do with it, but I have to talk about pathnames and directories a bit first.

cd

To change your working directory (where you are standing in the maze) you use the cd command. To do this, type cd followed by the pathname of the desired working directory. A pathname is the route you take along the branches of the tree to get to the directory you want. Pathnames can be specified in one of two different ways; absolute pathnames or relative pathnames. Let's deal with absolute pathnames first.

An absolute pathname begins with the root directory and follows the tree branch by branch until the path to the desired directory or file is completed. For example, there is a directory on your system in which documentation is stored. The pathname of the directory is /usr/share/doc. This means from the root directory (represented by the leading slash in the pathname) there is a directory called "usr" which contains a directory called "share" which contains a directory called "doc".

Let's try this out:

[me@shellium me]$ cd /usr/share/doc

[me@shellium me]$ pwd
/usr/share/doc

[me@linuxbox bin]$ ls
acl             fontconfig         libexif               libxslt-1.1.26         qwt
attr            gecko-mediaplayer  libgphoto2            libxslt-python-1.1.26  randrproto
automake        gettext            libgphoto2_port       libXvMC                renderproto
cairomm-1.0     gnome-mplayer      libmtp-1.0.2          Linux-PAM              rp-pppoe-3.10

etc...

Now we can see that we have changed the current working directory to /usr/share/doc and that it is full of files. Notice how your prompt has changed? As a convenience, it is usually set up to display the name of the working directory.

Where an absolute pathname starts from the root directory and leads to its destination, a relative pathname starts from the working directory. To do this, it uses a couple of special symbols to represent relative positions in the file system tree. These special symbols are "." (dot) and ".." (dot dot).

The "." symbol refers to the working directory and the ".." symbol refers to the working directory's parent directory. Here is how it works. Let's change the working directory to /usr/share/doc again:

[me@shellium me]$ cd /usr/share/doc
[me@shellium doc]$ pwd
/usr/share/doc

Now let's say that we wanted to change the working directory to the parent of /usr/share/doc which is /usr/share. We could do that two different ways. First, with an absolute pathname:

[me@shellium doc]$ cd /usr/share
[me@shellium share]$ pwd
/usr/share

Or, with a relative pathname:

[me@shellium doc]$ cd ..
[me@shellium share]$ pwd
/usr/share

Two different methods with identical results. Which one should you use? The one that requires less typing!

Likewise, we can change the working directory from /usr/share to /usr/share/doc in two different ways. First using an absolute pathname:

[me@shellium share]$ cd /usr/share/doc
[me@shellium doc]$ pwd
/usr/share/doc

Or, with a relative pathname:

[me@shellium share]$ cd ./doc
[me@shellium doc]$ pwd
/usr/share/doc

Now, there is something important that I must point out here. In almost all cases, you can omit the "./". It is implied. Typing:

[me@shellium share]$ cd doc

Would do the same thing. In general, if you do not specify a pathname to something, the working directory will be assumed. There is one important exception to this, but we won't get to that for a while.

Shortcuts

If you type cd followed by nothing, cd will change the working directory to your home directory.

cd ~ will also return you to your home directory.

A related shortcut is to type cd ~user_name. In this case, cd will change the working directory to the home directory of the specified user.

Important Notes

  1. File names that begin with a period character are hidden. This only means that ls will not list them unless you say ls -a. When your account was created, several hidden files were placed in your home directory to configure things for your account. Later on we will take a closer look at some of these files to see how you can customize your environment. In addition, some applications will place their configuration and settings files in your home directory as hidden files.
  2. File names in Linux, like Unix, are case sensitive. The file names "File1" and "file1" refer to different files.
  3. Linux has no concept of a "file extension" like legacy operating systems. You may name files any way you like. The contents/purpose of a file is determined by other means.
  4. While Linux supports long file names which may contain embedded spaces and punctuation characters, limit the punctuation characters to period, dash, and underscore. Most importantly, do not embed spaces in file names. If you want to represent spaces between words in a file name, use underscore characters. You will thank yourself later.

Looking Around

Now that you know how to move from working directory to working directory, we're going to take a tour of your Linux system and, along the way, learn some things about what makes it tick. But before we begin, I have to teach you some tools that will come in handy during our adventure. These are:

  • ls (list files and directories)
  • less (view text files)
  • file (classify a file's contents)

ls

The ls command is used to list the contents of a directory. It is probably the most commonly used Linux command. It can be used in a number of different ways. Here are some examples:

Command Result
ls List the (visible) files in the working directory.
ls /bin List the (visible) files in the /bin directory (or any other directory you care to specify)
ls -l List the (visible) files in the working directory in long format.
ls -l /etc /bin List the (visible) files in the /bin directory and the /etc directory in long format
ls -la .. List all files (even ones with names beginning with a period character, which are normally hidden) in the parent of the working directory in long format.

These examples also point out an important concept about commands. Most commands operate like this:

command -options arguments

where command is the name of the command, -options is one or more adjustments to the command's behavior, and arguments is one or more "things" upon which the command operates.

In the case of ls, we see that ls is the name of the command, and that it can have one or more options, such as -a and -l (also -al or -la), and it can operate on one or more files or directories.

Long Format

If you use the -l option with ls, you will get a file listing that contains a wealth of information about the files being listed. Here's an example:

-rw-------   1 usrname  grpname       576 Apr 17  2010 weather.txt
drwxr-xr-x   6 usrname  grpname      1024 Oct  9  2010 web_page
-rw-rw-r--   1 usrname  grpname    276480 Feb 11 20:41 web_site.tar
-rw-------   1 usrname  grpname      5743 Dec 16  2009 xmas_file.txt

----------     -------  -------  -------- ------------ -------------
    |             |        |         |         |             |
    |             |        |         |         |         File Name
    |             |        |         |         |
    |             |        |         |         +---  Modification Time
    |             |        |         |
    |             |        |         +-------------   Size (in bytes)
    |             |        |
    |             |        +-----------------------        Group
    |             |
    |             +--------------------------------        Owner
    |
    +----------------------------------------------   File Permissions
  • File Name - The name of the file or directory.
  • Modification Time - The last time the file was modified. If the last modification occurred more than six months in the past, the date and year are displayed. Otherwise, the time of day is shown.
  • Size - The size of the file in bytes.
  • Group - The name of the group that has file permissions in addition to the file's owner.
  • Owner - The name of the user who owns the file.
  • File Permissions - A representation of the file's access permissions. The first character is the type of file. A "-" indicates a regular (ordinary) file. A "d" indicates a directory. The second set of three characters represent the read, write, and execution rights of the file's owner. The next three represent the rights of the file's group, and the final three represent the rights granted to everybody else.

less

less is a program that lets you view text files. This is very handy since many of the files used to control and configure Linux are human readable (as opposed to some other operating systems).

What is "text"?

There are many ways to represent information on a computer. All methods involve defining a relationship between the information and some numbers that will be used to represent it. Computers, after all, only understand numbers and all data is converted to numeric representation.

Some of these representation systems are very complex (such as compressed image files), while others are rather simple. One of the earliest and simplest is called ASCII text. ASCII (pronounced "As-Key") is short for American Standard Code for Information Interchange. This is a simple encoding scheme that was first used on Teletype machines to map keyboard characters to numbers.

Text is a simple one-to-one mapping of characters to numbers. It is very compact. Fifty characters of text translates to fifty bytes of data. Throughout a Linux system, many files are stored in text format and there are many Linux tools that work with text files. Even the legacy operating systems recognize the importance of this format. The well-known NOTEPAD.EXE program is an editor for plain ASCII text files.

The less program is invoked by simply typing:

[me@shellium me]$ less text_file

This will display the file. Once started, less will display the text file one page at a time. You may use the Page Up and Page Down keys to move through the text file. To exit less, type "q". Here are some commands that less will accept:

Command Action
Up Arrow Scroll up one line of the document at a time.
Down Arrow Scroll down one line of the document at at a time.
Page Up or b Scroll back one page.
Page Down or space Scroll forward one page.
G Go to the end of the text file.
1G Go to the beginning of the text file.
/characters Search forward in the text file for an occurence of the specified characters.
n Repeat the previous search.
q Quit

file

As you wander around your Linux system, it is helpful to determine what a file contains before you try to view it. This is where the file command comes in. file will examine a file and tell you what kind of file it is.

To use the file program, just type:

[me@shellium me]$ file name_of_file

The file program can recognize most types of files, such as:

File Type Description Viewable as text?
ASCII text The name says it all yes
Bourne-Again shell script text A bash script yes
ELF 32-bit LSB core file A core dump file (a program will create this when it crashes) no
ELF 32-bit LSB executable An executable binary program no
ELF 32-bit LSB shared object A shared library no
GNU tar archive A tape archive file. A common way of storing groups of files. no, use tar tvf to view listing.
gzip compressed data An archive compressed with gzip no
HTML document text A web page yes
JPEG image data A compressed JPEG image no
PostScript document text A PostScript file yes
RPM A Red Hat Package Manager archive no, use rpm -q to examine contents.
Zip archive data An archive compressed with zip no

While it may seem that most files cannot be viewed as text, you will be surprised how many can. This is especially true of the important configuration files. You will also notice during our adventure that many features of the operating system are controlled by shell scripts. In Linux, there are no secrets!

Manipulating Files

This lesson will introduce you to the following commands:

  • cp - copy files and directories
  • mv - move or rename files and directories
  • rm - remove files and directories
  • mkdir - create directories

These four commands are among the most frequently used Linux commands. They are the basic commands for manipulating both files and directories.

Now, to be frank, some of the tasks performed by these commands are more easily done with a graphical file manager. With a file manager, you can drag and drop a file from one directory to another, cut and paste files, delete files, etc. So why use these old command line programs?

The answer is power and flexibility. While it is easy to perform simple file manipulations with a graphical file manager, complicated tasks can be easier with the command line programs. For example, how would you copy all the HTML files from one directory to another, but only copy files that did not exist in the destination directory or were newer than the versions in the destination directory? Pretty hard with a file manager. Pretty easy with the command line:

[me@shellium me]$ cp -u *.html destination

Wildcards

Before I begin with our commands, I want to talk about a shell feature that makes these commands so powerful. Since the shell uses filenames so much, it provides special characters to help you rapidly specify groups of filenames. These special characters are called wildcards. Wildcards allow you to select filenames based on patterns of characters. The table below lists the wildcards and what they select:

Wildcard Meaning
* Matches any characters
? Matches any single character
[characters] Matches any character that is a member of the set characters. The set of characters may also be expressed as a POSIX character class such as one of the following:
Posix Character Classes
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:digit:] Numerals
[:upper:] Uppercase alphabetic characters
[:lower:] Lowercase alphabetic characters
[!characters] Matches any character that is not a member of the set characters

Using wildcards, it is possible to construct very sophisticated selection criteria for filenames. Here are some examples of patterns and what they match:

Pattern Matches
* All filenames
g* All filenames that begin with the character "g"
b*.txt All filenames that begin with the character "b" and end with the characters ".txt"
Data??? Any filename that begins with the characters "Data" followed by exactly 3 more characters
[abc]* Any filename that begins with "a" or "b" or "c" followed by any other characters
[[:upper:]]* Any filename that begins with an uppercase letter. This is an example of a character class.
BACKUP.[[:digit:]][[:digit:]] Another example of character classes. This pattern matches any filename that begins with the characters "BACKUP." followed by exactly two numerals.
*[![:lower:]] Any filename that does not end with a lowercase letter.

You can use wildcards with any command that accepts filename arguments.

cp

The cp program copies files and directories. In its simplest form, it copies a single file:

[me@shellium me]$ cp sourcefilename destinationfilename

It can also be used to copy multiple files to a different directory:

[me@shellium me]$ cp file1 file2 file3 /directory

Other useful examples of cp and its options include:

Command Results
cp file1 file2 Copies the contents of file1 into file2. If file2 does not exist, it is created; otherwise, file2 is overwritten with the contents of file1.
cp -i file1 file2 Like above however, since the "-i" (interactive) option is specified, if file2 exists, the user is prompted before it is overwritten with the contents of file1.
cp file1 dir1 Copy the contents of file1 (into a file named file1) inside of directory dir1.
cp -R dir1 dir2 Copy the contents of the directory dir1. If directory dir2 does not exist, it is created. Otherwise, it creates a directory named dir1 within directory dir2.

For a complete explanation of all cp options, see man cp from the command line.

mv

The mv command performs two different functions depending on how it is used. It will either move one or more files to a different directory, or it will rename a file or directory. To rename a file, it is used like this:

[me@shellium me]$ mv filename1 filename2

To move files to a different directory:

[me@shellium me]$ mv file1 file2 file3 directory

Examples of mv and its options include:

Command Results
mv file1 file2 If file2 does not exist, then file1 is renamed file2. If file2 exists, its contents are replaced with the contents of file1.
mv -i file1 file2 Like above however, since the "-i" (interactive) option is specified, if file2 exists, the user is prompted before it is overwritten with the contents of file1.
mv file1 file2 file3 dir1 The files file1, file2, file3 are moved to directory dir1. dir1 must exist or mv will exit with an error.
mv dir1 dir2 If dir2 does not exist, then dir1 is renamed dir2. If dir2 exists, the directory dir1 is created within directory dir2.

rm

The rm command deletes (removes) files and directories.

[me@shellium me]$ rm file

It can also be used to delete a directory:

[me@shellium me]$ rm -r directory

Examples of rm and its options include:

Command Results
rm file1 file2 Delete file1 and file2.
rm -i file1 file2 Like above however, since the "-i" (interactive) option is specified, the user is prompted before each file is deleted.
rm -r dir1 dir2 Directories dir1 and dir2 are deleted along with all of their contents.


Be careful with rm!

Linux does not have an undelete command. Once you delete a file with rm, it's gone. You can inflict terrific damage on your system with rm if you are not careful, particularly with wildcards.

Before you use rm with wildcards, try this helpful trick: construct your command using ls instead. By doing this, you can see the effect of your wildcards before you delete files. After you have tested your command with ls, recall the command with the up-arrow key and then substitute rm for ls in the command.

mkdir

The mkdir command is used to create directories. To use it, you simply type:

[me@shellium me]$ mkdir directory

I/O Redirection

As we have seen, many commands such as ls print their output on the display. This does not have to be the case, however. By using some special notation we can redirect the output of many commands to files, devices, and even to the input of other commands.

Standard Output

Most command line programs that display their results do so by sending their results to a facility called standard output. By default, standard output directs its contents to the display. To redirect standard output to a file, the ">" character is used like this:

[me@shellium me]$ ls > file_list.txt

In this example, the ls command is executed and the results are written in a file named file_list.txt. Since the output of ls was redirected to the file, no results appear on the display.

Each time the command above is repeated, file_list.txt is overwritten (from the beginning) with the output of the command ls. If you want the new results to be appended to the file instead, use ">>" like this:

[me@shellium me]$ ls >> file_list.txt

When the results are appended, the new results are added to the end of the file, thus making the file longer each time the command is repeated. If the file does not exist when you attempt to append the redirected output, the file will be created.

Standard Input

Many commands can accept input from a facility called standard input. By default, standard input gets its contents from the keyboard, but like standard output, it can be redirected. To redirect standard input from a file instead of the keyboard, the "<" character is used like this:

[me@shellium me]$ sort < file_list.txt

In the above example we used the sort command to process the contents of file_list.txt. The results are output on the display since the standard output is not redirected in this example. We could redirect standard output to another file like this:

[me@shellium me]$ sort < file_list.txt > sorted_file_list.txt

As you can see, a command can have both its input and output redirected. Be aware that the order of the redirection does not matter. The only requirement is that the redirection operators (the "<" and ">") must appear after the other options and arguments in the command.

Pipes

By far, the most useful and powerful thing you can do with I/O redirection is to connect multiple commands together with what are called pipes. With pipes, the standard output of one command is fed into the standard input of another. Here is my absolute favorite:

[me@shellium me]$ ls -l | less

In this example, the output of the ls command is fed into less. By using this "| less" trick, you can make any command have scrolling output. This technique is quite useful and common to all *NIX users.

By connecting commands together, you can acomplish amazing feats. Here are some examples you'll want to try:

Examples of commands used together with pipes

Command Results
ls -lt | head Displays the 10 newest files in the current directory.
du | sort -nr Displays a list of directories and how much space they consume, sorted from the largest to the smallest.
find . -type f -print | wc -l Displays the total number of files in the current working directory and all of its subdirectories.

Filters

One class of programs you can use with pipes is called filters. Filters take standard input and perform an operation upon it and send the results to standard output. In this way, they can be used to process information in powerful ways. Here are some of the common programs that can act as filters:

Program What it does
sort Sorts standard input then outputs the sorted result on standard output.
uniq Given a sorted stream of data from standard input, it removes duplicate lines of data (i.e., it makes sure that every line is unique).
grep Examines each line of data it receives from standard input and outputs every line that contains a specified pattern of characters.
fmt Reads text from standard input, then outputs formatted text on standard output.
pr Takes text input from standard input and splits the data into pages with page breaks, headers and footers in preparation for printing.
head Outputs the first few lines of its input. Useful for getting the header of a file.
tail Outputs the last few lines of its input. Useful for things like getting the most recent entries from a log file.
tr Translates characters. Can be used to perform tasks such as upper/lowercase conversions or changing line termination characters from one type to another (for example, converting DOS text files into Unix style text files).
sed Stream editor. Can perform more sophisticated text translations than tr.
awk An entire programming language designed for constructing filters. Extremely powerful.

For a complete list of options for each program, see it's man page.

Performing tasks with pipes

  • Printing from the command line. Linux provides a program called lpr that accepts standard input and sends it to the printer. It is often used with pipes and filters. Here are a couple of examples:
cat poorly_formatted_report.txt | fmt | pr | lpr
cat unsorted_list_with_dupes.txt | sort | uniq | pr | lpr

In the first example, we use cat to read the file and output it to standard output, which is piped into the standard input of fmt. fmt formats the text into neat paragraphs and outputs it to standard output, which is piped into the standard input of pr. pr splits the text neatly into pages and outputs it to standard output, which is piped into the standard input of lpr. lpr takes its standard input and sends it to the printer.

The second example starts with an unsorted list of data with duplicate entries. First, cat sends the list into sort which sorts it and feeds it into uniq which removes any duplicates. Next pr and lpr are used to paginate and print the list.

  • Viewing the contents of tar files Often you will see software distributed as a gzipped tar file. This is a traditional Unix style tape archive file (created with tar) that has been compressed with gzip. You can recognize these files by their traditional file extensions, ".tar.gz" or ".tgz". You can use the following command to view the directory of such a file on a Linux system:
tar tzvf name_of_file.tar.gz | less

Permissions

The Unix operating system (and likewise, Linux) differs from other computing environments in that it is not only a multitasking system but it is also a multi-user system as well.

What exactly does this mean? It means that more than one user can be operating the computer at the same time. While your computer will only have one keyboard and monitor, it can still be used by more than one user. For example, if your computer is attached to a network, or the Internet, remote users can log in via telnet or ssh (secure shell) and operate the computer. In fact, remote users can execute X applications and have the graphical output displayed on a remote computer. The X Windows system supports this.

The multi-user capability of Unix is not a recent "innovation," but rather a feature that is deeply ingrained into the design of the operating system. If you remember the environment in which Unix was created, this makes perfect sense. Years ago before computers were "personal," they were large, expensive, and centralized. A typical university computer system consisted of a large mainframe computer located in some building on campus and terminals were located throughout the campus, each connected to the large central computer. The computer would support many users at the same time.

In order to make this practical, a method had to be devised to protect the users from each other. After all, you could not allow the actions of one user to crash the computer, nor could you allow one user to interfere with the files belonging to another user.

This lesson will cover the following commands:

  • chmod - modify file access rights
  • su - temporarily become the superuser
  • chown - change file ownership
  • chgrp - change a file's group ownership

Files

Linux uses the same permissions scheme as Unix. Each file and directory on your system is assigned access rights for the owner of the file, the members of a group of related users, and everybody else. Rights can be assigned to read a file, to write a file, and to execute a file (i.e., run the file as a program).

To see the permission settings for a file, we can use the ls command as follows:

[me@shellium me]$ ls -l some_file

-rw-rw-r-- 1 me   me   1097374 Sep 26 18:48 some_file

We can determine a lot from examining the results of this command:

  • The file "some_file" is owned by user "me"
  • User "me" has the right to read and write this file
  • The file is owned by the group "me"
  • Members of the group "me" can also read and write this file
  • Everybody else can read this file

Let's try another example. We will look at the bash program which is located in the /bin directory:

[me@shellium me]$ ls -l /bin/bash

-rwxr-xr-x 1 root root  316848 Feb 27  2000 /bin/bash

Here we can see:

  • The file "/bin/bash" is owned by user "root"
  • The superuser has the right to read, write, and execute this file
  • The file is owned by the group "root"
  • Members of the group "root" can also read and execute this file
  • Everybody else can read and execute this file
  • In the diagram below, we see how the first portion of the listing is interpreted. It consists of a character indicating the file type, followed by three sets of three characters that convey the reading, writing and execution permission for the owner, group, and everybody else.
- rwx r-x r-x
|  |   |   |
|  |   |   +- read, write and execute permissions for all users
|  |   +----- read, write and execute permissions for members of the group owning the file
|  +--------- read, write and execute permissions for the owner of the file
+------------ file type "-" indicates a regular file, "d" indicates a directory, "l" is a link

chmod

The chmod command is used to change the permissions of a file or directory. To use it, you specify the desired permission settings and the file or files that you wish to modify. There are two ways to specify the permissions, but I am only going to teach one way.

It is easy to think of the permission settings as a series of bits (which is how the computer thinks about them). Here's how it works:

rwx rwx rwx = 111 111 111
rw- rw- rw- = 110 110 110
rwx --- --- = 111 000 000

and so on...

rwx = 111 in binary = 7
rw- = 110 in binary = 6
r-x = 101 in binary = 5
r-- = 100 in binary = 4

Files

Now, if you represent each of the three sets of permissions (owner, group, and other) as a single digit, you have a pretty convenient way of expressing the possible permissions settings. For example, if we wanted to set some_file to have read and write permission for the owner, but wanted to keep the file private from others, we would:

[me@shellium me]$ chmod 600 some_file

Here is a table of numbers that covers all the common settings. The ones beginning with "7" are used with programs (since they enable execution) and the rest are for other kinds of files.

Value Meaning
777 (rwxrwxrwx) No restrictions on permissions. Anybody may do anything. Generally not a desirable setting.
755 (rwxr-xr-x) The file's owner may read, write, and execute the file. All others may read and execute the file. This setting is common for programs that are used by all users.
700 (rwx------) The file's owner may read, write, and execute the file. Nobody else has any rights. This setting is useful for programs that only the owner may use and must be kept private from others.
666 (rw-rw-rw-) All users may read and write the file.
644 (rw-r--r--) The owner may read and write a file, while all others may only read the file. A common setting for data files that everybody may read, but only the owner may change.
600 (rw-------) The owner may read and write a file. All others have no rights. A common setting for data files that the owner wants to keep private.

Directories

The chmod command can also be used to control the access permissions for directories. In most ways, the permissions scheme for directories works the same way as they do with files. However, the execution permission is used in a different way. It provides control for access to file listing and other things. Here are some useful settings for directories:

Value Meaning
777 (rwxrwxrwx) No restrictions on permissions. Anybody may list files, create new files in the directory and delete files in the directory. Generally not a good setting.
755 (rwxr-xr-x) The directory owner has full access. All others may list the directory, but cannot create files nor delete them. This setting is common for directories that you wish to share with other users.
700 (rwx------) The directory owner has full access. Nobody else has any rights. This setting is useful for directories that only the owner may use and must be kept private from others.

Super User

Although it is highly unlikely a normal user would ever be given the permissions to use the super user (root) account on their SHellium account, I will add this purely for educational purposes and those wishing to learn in their own environment.

su

It is often useful to become the superuser to perform important system administration tasks, but as you have been warned (and not just by me!), you should not stay logged on as the superuser. In most distributions, there is a program that can give you temporary access to the superuser's privileges. This program is called su (short for substitute user) and can be used in those cases when you need to be the superuser for a small number of tasks. To become the superuser, simply type the su command. You will be prompted for the superuser's password:

[me@linuxbox me]$ su
Password:
[root@linuxbox me]#

After executing the su command, you have a new shell session as the superuser. To exit the superuser session, type exit and you will return to your previous session.

In some distributions, most notably Ubuntu, an alternate method is used. Rather than using su, these systems employ the sudo command instead. With sudo, one or more users are granted superuser privileges on an as needed basis. To execute a command as the superuser, the desired command is simply preceeded with the sudo command. After the command is entered, the user is prompted for the user's password rather than the superuser's:

[me@linuxbox me]$ sudo some_command
Password:
[me@linuxbox me]$

Changing file ownership

You can change the owner of a file by using the chown command. Here's an example: Suppose I wanted to change the owner of some_file from "me" to "you". You could:

[me@linuxbox me]$ su
Password:
[root@linuxbox me]# chown you some_file
[root@linuxbox me]# exit
[me@linuxbox me]$

Notice that in order to change the owner of a file, you must be the superuser. To do this, our example employed the su command, then we executed chown, and finally we typed exit to return to our previous session.

chown works the same way on directories as it does on files. chown -R user directory would change permissions recursively (on all files and directories under the target).

Changing group ownership

The group ownership of a file or directory may be changed with chgrp. This command is used like this:

[me@linuxbox me]$ chgrp new_group some_file

In the example above, we changed the group ownership of some_file from its previous group to "new_group". You must be the owner of the file or directory to perform a chgrp. The -R switch is also valid for directories and will change permissions recursively.

Job Control

In the previous lesson, we looked at some of the implications of Linux being a multi-user operating system. In this lesson, we will examine the multitasking nature of Linux, and how this is manipulated with the command line interface.

As with any multitasking operating system, Linux executes multiple, simultaneous processes. Well, they appear simultaneous, anyway. Actually, a single processor computer can only execute one process at time but the Linux kernel manages to give each process its turn at the processor and each appears to be running at the same time.

There are several commands that can be used to control processes. They are:

  • ps - list the processes running on the system
  • kill - send a signal to one or more processes (usually to "kill" a process)
  • jobs - an alternate way of listing your own processes
  • bg - put a process in the background
  • fg - put a process in the forground

bg

To run a program and immediately place it in the background, simply append an "&" (ampersand) to the end of the command line as follows:

[me@shellium me]$ eggdrop eggdrop.conf &
[1] 1246

[me@shellium me]$

You will notice that the prompt returned because the process is running in the background, allowing you to go about other business.

Now imagine that you forgot to use the "&" symbol to put the program into the background. There is still hope. You can type control-z and the process will be suspended. The process still exists, but is idle. To resume the process in the background, type the bg command (short for background). Here is an example:

[me@shellium me]$ eggdrop eggdrop.conf 
# (press ctrl-z)
[2]+ Stopped xload

[me@shellium me]$ bg
[2]+ xload &

Eggdrop will resume normal operations in the background, and you can go back to working at the command line.

jobs

Now that we have a process in the background, it would be helpful to display a list of the processes we have launched. To do this, we can use either the jobs command

[me@shellium me]$ jobs
[1]+ Running eggdrop &

[me@shellium me]$

ps

Or the more powerful ps command:

[me@shellium me]$ ps
PID TTY TIME CMD
1211 pts/4 00:00:00 bash
1246 pts/4 00:00:00 eggdrop
1247 pts/4 00:00:00 ps

[me@shellium me]$

For additional information, ps with the use of some switches may be piped to grep to produce something like:

[me@shellium me]$ ps aux | grep me
me        1211  0.0  0.2   7812  4012 pts/142  Ss   13:16   0:00 -bash
me        1246  0.0  0.7  21648 11760 pts/3    S    13:44   0:05 /usr/bin/eggdrop eggdrop.conf &
me        3124  0.0  0.0   4792  1032 pts/3    R+   15:59   0:00 ps aux

[me@shellium me]$

kill

Suppose that you have a program that becomes unresponsive; how do you get rid of it? You use the kill command, of course. Let's try this out on eggdrop. First, you need to identify the process you want to kill. You can use either jobs or ps, to do this. If you use jobs you will get back a job number. With ps, you are given a process id (PID). We will do it both ways: (by job number)

[me@shellium me]$ eggdrop eggdrop.conf &
[1] 1246

[me@shellium me]$ jobs
[1]+ Running eggdrop &

[me@shellium me]$ kill %1
[2] 1293
[1] Terminated eggdrop

Had eggdrop been running as job 4, "kill %4" would have be issued. Now, by PID:

[me@shellium me]$ ps
PID TTY TIME CMD
1280 pts/5 00:00:00 bash
1293 pts/5 00:00:00 xload
1294 pts/5 00:00:00 ps

[me@shellium me]$ kill 1293
[2]+ Terminated eggdrop
[me@linuxbox me]$

Signals

While the kill command is used to "kill" processes, its real purpose is to send signals to processes. Most of the time the signal is intended to tell the process to go away, but there is more to it than that. Programs (if they are properly written) listen for signals from the operating system and respond to them, most often to allow some graceful method of terminating. For example, a text editor might listen for any signal that indicates that the user is logging off, or that the computer is shutting down. When it receives this signal, it saves the work in progress before it exits. The kill command can send a variety of signals to processes. Typing:

    kill -l

will give you a list of the signals it supports. Most are rather obscure, but several are useful to know:

Signal # Name Description
1 SIGHUP Hang up signal. Programs can listen for this signal and act (or not act) upon it.
2 SIGINT Interrupt signal. This signal is given to processes to interrupt them. Programs can process this signal and act upon it. You can also issue this signal directly by typing control-c in the terminal window where the program is running.
15 SIGTERM Termination signal. This signal is given to processes to terminate them. Again, programs can process this signal and act upon it. You can also issue this signal directly by typing control-c in the terminal window where the program is running. This is the default signal sent by the kill command if no signal is specified.
9 SIGKILL Kill signal. This signal causes the immediate termination of the process by the Linux kernel. Programs cannot listen for this signal.

Now let's suppose that you have a program that is hopelessly hung (Netscape, maybe) and you want to get rid of it. Here's what you do:

  1. Use the ps command to get the process id (PID) of the process you want to terminate.
  2. Issue a kill command for that PID.
  3. If the process refuses to terminate (i.e., it is ignoring the signal), send increasingly harsh signals until it does terminate.
[me@shellium me]$ ps x
PID TTY STAT TIME COMMAND
2931 pts/5 SN 0:00 someprogram
[me@shellium me]$ kill -SIGTERM 2931
[me@shellium me]$ kill -SIGKILL 2931

In the example above I used the kill command in the formal way. In actual practice, it is more common to do it in the following way since the default signal sent by kill is SIGTERM and kill can also use the signal number instead of the signal name:

[me@shellium me]$ kill 2931

Then, if the process does not terminate, force it with the SIGKILL signal:

[me@shellium me]$ kill -9 2931
Personal tools
Namespaces

Variants
Actions
Navigation
Indexes
SHellium Sites
Toolbox