Linux Commands and Examples


A Linux/UNIX system with many programs and packages installed may have thousands of available commands. These programs and tools implement capabilities such as faxing, imaging or web browsing and enable the user to interface and control the computer.

This page links to examples and documentation for most standard Linux commands and introduces core concepts with examples of their use.

Core Concepts

Linux commands share a standard input/output model (stdin/stdout ) and interact with the command line interpreter (bash,tcsh,etc) in a standard way. In order to understand and leverage Linux/Unix commands, a basic understanding of i/o, pipes, command line interpretation, signals, redirection and the shell(s) are useful. These concepts and others are described below.

Command Documentation

Linux distributions include on line reference manuals. The "man" command is used to search and display this reference material. The "man" command takes the name of a program, utility or function as it argument. For example: "man man" provides details on the capabilities and options available for the man command itself.

This documentation is often referred to as the man pages. The man pages are divided into sections and describe the commands, their usage, what they do and available options. The Linux Man Pages Project, GNU Manuals Online and Sarata Manpages are also great sources for Linux command documentation and information.

Linux Man Page Sections

1   Commands (Executable programs or shell commands)

2   System calls (functions provided by the kernel)

3   Library calls (functions within program libraries)

4   Special files (usually found in /dev)

5   File formats and conventions e.g. /etc/passwd

6   Games

7   Miscellaneous (including macro packages and conventions)

8   System administration commands (usually only for root)

A lot of GNU/FSF software is provided with info files. Type "info info" for an introduction on the use of the program "info". See the GNU Info Manual for more detail on the info command.

Special topics are often treated in HOWTOs. Look in /usr/share/doc/howto/en and use a browser if you find HTML files there.

Logging In:

In order to login to a Linux system you must have an account. Your account, group and the command to be executed upon successful authentication are generally set up by your system administrator. To login you must provide the account name and an associated password to the system.

The system prompts users for authentication through a GUI (graphical User Interface) or from a command line. Upon successful authentication, the login process begins a new session where the command identified in the user password file entry is executed. That command will usually be a command interpreter or shell. The shell is started and configured according to the password file specifications and is modified by the accounts startup profile.

Command Line Interpreter or shell

The command line interpreter(shell) is your primary interface to the computer. The function of the shell is to interpret and execute commands read from a command line string, the standard input, or a specified file. The shell is also a program and there are many versions to choose from; see bash(1), csh(1), zsh(1), chsh(1). When a command is presented to the shell it checks the syntax, executes the called built-in or Linux commands and takes control when these commands complete.

The shell prints a prompt (character or string) to let the user know that the system is ready to receive input. Input is provided by the user typing in commands (requests to do something) followed by a carriage return.

A command is a sequence of words and potentially options, separated by blanks and/or redirections and terminated by a control operator. The first word of the command string is the name of the program/command to execute. The shell searches for a program matching that name in the "path" that is defined for the shell. The first instance of a command matching the command name is executed. The options/arguments if there are any are passed to the command at execution time. The return value of the command is its exit status.

Command Execution Environment

The shell has an execution environment, which consists of the following:

•  open files inherited by the shell at invocation, as modified by redirections supplied to the exec builtin

•   the current working directory as set by cd, pushd, or popd, or inherited by the shell at invocation

•   the file creation mode mask as set by umask or inherited from the shell’s parent

•   current traps set by trap

•   shell parameters that are set by variable assignment or with set or inherited from the shell’s parent in the environment

•   shell functions defined during execution or inherited from the shell’s parent in the environment

•   options enabled at invocation (either by default or with command-line arguments) or by set

•   options enabled by shopt

•   shell aliases defined with alias

•   various process IDs, including those of background jobs, the value of $$, and the value of PPID

Example 1: Simple commands with no options

% cd
% pwd
/u/adam
% echo hello
hello

Example 2: redirection

% echo hello > greeting
% ls /usr/bin > cmdlist

Example 3: commands with options

% ls -i
19306988 cmdlist 19307014 greetings
% ls -l
total 36
-rw-r--r-- 1 adam users 32102 Jun 15 23:12 cmdlist
-rw-r--r-- 1 adam users 6 Jun 15 23:08 greetings

Example 4: command expansion

% ls -l g*
-rw-r--r-- 1 adam users 6 Jun 15 23:08 greetings
% ls -l *
-rw-r--r-- 1 adam users 32102 Jun 15 23:12 cmdlist
-rw-r--r-- 1 adam users 6 Jun 15 23:08 greetings
% ls -l [a-z]*
-rw-r--r-- 1 adam users 32102 Jun 15 23:12 cmdlist
-rw-r--r-- 1 adam users 6 Jun 15 23:08 greetings

control operator

Control operators are tokens that instruct the command interpreter to modify or control some aspect of the command execution. The control tokens are as follows:

|| & && ; ;; ( ) | |& <newline>

Pipelines

A pipeline is a sequence of one or more commands separated by one of the control operators | or |&. The format for a pipeline is:

[time [-p]] [ ! ] command [ [|

a command is terminated by the control operator &, the shell executes the command in the background in a subshell Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn AND and OR lists are sequences of one of more pipelines separated by the && and || control operators

Example 5: pipes

% ls /usr/bin | wc
3169 3169 32102
%

In the previous example the output of the command "ls /usr/bin" would generally be the terminal where the command is input. The use of the pipe symbol "|" redirects the input to the command wc.

Pattern Matching

The characters *, ?, and [ may also appear on the command line and are considered as patterns. When one of these characters is present on the command line they are replaced with an alphabetically sorted list of file names matching the pattern. Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The special pattern characters have the following meanings:

*       Matches any string, including the null string
?      Matches any single character
[...]   Matches any one of the enclosed characters

The interpretation of these characters on the command line can be modified using backslashes and/or quote characters. See the man page for the shell being used for more details.

Example 6: Expansion with multiple commands

The following command will print the size and name of the largest file or directory in the current directory

% du -s * | sort -nr | head -1
1107552 TESTDIR

REDIRECTION

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection may also be used to open and close files for the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.

Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than 10 and assign it to varname. If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close.

In the following descriptions, if the file descriptor number is omitted, and the first character of the redirection operator is <, the redirection refers to the standard input (file descriptor 0). If the first character of the redirection operator is >, the redirection refers to the standard output (file descriptor 1).

The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic expansion, quote removal, pathname expansion, and word splitting. If it expands to more than one word, the shell reports an error.

Note that the order of redirections is significant. For example, the command

ls > dirlist 2>&1

directs both standard output and standard error to the file dirlist, while the command

ls 2>&1 > dirlist

The command above directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist.

Redirecting Input

Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.

The general format for redirecting input is:

[n]<word

Redirecting Output

Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.

The general format for redirecting output is:

[n]>word

If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is >|, or the redirection operator is > and the noclobber option to the set builtin command is not enabled, the redirection is attempted even if the file named by word exists.

Appending Redirected Output

Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created.

The general format for appending output is:

[n]>>word

Redirecting Standard Output and Standard Error

This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word.

There are two formats for redirecting standard output and standard error:

&>word
and
>&word

Of the two forms, the first is preferred. This is semantically equivalent to

>word 2>&1

Appending Standard Output and Standard Error

This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be appended to the file whose name is the expansion of word.

The format for appending standard output and standard error is:

&>>word

This is semantically equivalent to

>>word 2>&1

EXIT STATUS

The exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fall between 0 and 255.

For the shell's purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure.

If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.

If a command fails because of an error during expansion or redirection, the exit status is greater than zero.

Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage.

SIGNALS

The default behavior for Linux shells and commands is to respond to signal such as SIGTERM,SIGINT, SIGQUIT and SIGTSTP. These signals cause commands to do things such as exit, suspend and/or resume their execution.

Job control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at a later point.

The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the jobs command.

The job number or process ID is used to deliver signals to the process of job.

PATH

Command interpreters search for commands based on a variable defined in the shell called a path. A path is essentially a string that contains a list of directories separated by the : character. When the shell receives a request it searches each directory in order looking for the named command to execute. The path for my account is as follows:

PATH=/home/adam/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games

Example 7: A session

knuth login: aeb
Password: ********
% date
Tue Aug 6 23:50:44 CEST 2002
% whereis date
date: /usr/bin/date /bin/date /usr/share/man/man1p/date.1p.gz /usr/share/man/man1/date.1.gz
% which date
/usr/bin/date
% cal
August 2002
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
% ls
bin tel
% ls -l
total 2
drwxrwxr-x 2 aeb 1024 Aug 6 23:51 bin
-rw-rw-r-- 1 aeb 37 Aug 6 23:52 tel
% cat tel
maja 0501-1136285
peter 0136-7399214
% cp tel tel2
% ls -l
total 3
drwxr-xr-x 2 aeb 1024 Aug 6 23:51 bin
-rw-r--r-- 1 aeb 37 Aug 6 23:52 tel
-rw-r--r-- 1 aeb 37 Aug 6 23:53 tel2
% mv tel tel1
% ls -l
total 3
drwxr-xr-x 2 aeb 1024 Aug 6 23:51 bin
-rw-r--r-- 1 aeb 37 Aug 6 23:52 tel1
-rw-r--r-- 1 aeb 37 Aug 6 23:53 tel2
% diff tel1 tel2
% rm tel1
% grep maja tel2
maja 0501-1136285
%

and here typing Control-D ended the session. The % here was the prompt command. It is the shell's way of indicating that it is ready for the next command. The prompt can be customized in lots of ways, and one might include stuff like username, machine name, current directory, time, and so on. An assignment PS1="What next, master?" would change the prompt as indicated.

We see that there are commands date (that gives date and time), and cal (that gives a calendar).

The whereis command shows locations for the program named date on the system and the which command shows which version of the data command was executed.

The command ls lists the contents of the current directory and tells you what files you have. With a -l option it gives a long listing, that includes the owner and size and date of the file, and the permissions people have for reading and/or changing the file. For example, the file "tel" here is 37 bytes long, owned by aeb and the owner can read and write it, others can only read it. Owner and permissions can be changed by the commands chown and chmod.

The command cat will show the contents of a file. (The name is from "concatenate and print": all files given as parameters are concatenated and sent to "standard output", here the terminal screen.)

The command cp (from "copy") will copy a file. On the other hand, the command mv (from "move") only renames it.

The command diff lists the differences between two files. Here there was no output because there were no differences.

The command rm (from "remove") deletes the file, and be careful! it is gone. No wastepaper basket or anything. Deleted means lost.

The command grep (from "g/re/p") finds occurrences of a string in one or more files. Here it finds Maja's telephone number.

Pathnames and the current directory

Files live in a large tree, the file hierarchy. Each has a pathname describing the path from the root of the tree (which is called /) to the file. For example, such a full pathname might be /home/aeb/tel. Always using full pathnames would be inconvenient, and the name of a file in the current directory may be abbreviated by giving only the last component. That is why "/home/aeb/tel" can be abbreviated to "tel" when the current directory is "/home/aeb".

The command pwd prints the current directory.

The command cd changes the current directory. Try "cd /" and "pwd" and "cd" and "pwd".

Directories

The command mkdir makes a new directory.

The command rmdir removes a directory if it is empty, and complains otherwise.

The command find (with a rather baroque syntax) will find files with given name or other properties. For example, "find . -name tel" would find the file "tel" starting in the present directory (which is called "."). And "find / -name tel" would do the same, but starting at the root of the tree. Large searches on a multi-GB disk will be time-consuming, and it may be better to use locate(1).

Disks and filesystems

The command mount will attach the filesystem found on some disk (or floppy, or CDROM or so) to the big filesystem hierarchy. And umount detaches it again. The command df will tell you how much of your disk is still free.

Processes

On a UNIX system many user and system processes run simultaneously. The one you are talking to runs in the foreground, the others in the background. The command ps will show you which processes are active and what numbers these processes have. The command kill allows you to get rid of them. Without option this is a friendly request: please go away. And "kill -9" followed by the number of the process is an immediate kill. Foreground processes can often be killed by typing Control-C.


Financial Opportunity

cross

Learn why free software provides the greatest opportunity on the planet today. Leverage the billions of dollars in resources and capabilities to build a career, establish a business or change the world. Learn ot use this opportunity and the potential is endless.


Study at Harvard, Stanford or MIT

sunrise

Open edX provides free online courses from Harvard, MIT, Columbia, UC Berkeley and other top Universities. Hundreds of courses for almost all major subjects and course levels. Open edx also offers some paid courses and selected certifications.


Free Office Software

cross

The Libre Office suite provides top desktop productivity tools for free. This includes, a word processor, spreadsheet, presentation engine, drawing and flowcharting, database and math applications. Libre Office is available for Linux or Windows.


What is Linux

study

Linux is an open source computer operating system (OS) used on laptops, games, watches and super computers. The software and the source code used for Linux are both available to you at no cost. Use this powerful resource to your advantage.


U.S. Government

words

On January 20 2009, President Obama's first day in office, the Open Government initiative was issued to provide transparency and access to Government data. Learn how our Government is using open source and the opportunities this provides for you.


Wall Street

bible genesis

Goldman Sachs, IBM and countless large corporations are leveraging open source to reduce costs, develop products and increase their bottom lines. Learn what these companies know about open source and how open source can give you the advantage.






Financial Opportunity


Personal Opportunity - Free software gives you access to billions of dollars of software at no cost. Use this software for your business, personal use or to develop a profitable skill. Access to source code provides access to a level of capabilities/information that companies protect though copyrights. Open source is a core component of the Internet and it is available to you. Leverage the billions of dollars in resources and capabilities to build a career, establish a business or change the world. The potential is endless for those who understand the opportunity.

Business Opportunity - Goldman Sachs, IBM and countless large corporations are leveraging open source to reduce costs, develop products and increase their bottom lines. Learn what these companies know about open source and how open source can give you the advantage.

U.S. Government - On January 20 2009, President Obama's first day in office, the Open Government initiative was issued to provide transparency and access to Government data. Learn how our Government is using open source and the opportunities this provides for you. Leverage Use open Government data or



Free Books


The Free Books Library is a collection of thousands of the most popular public domain books in an online readable format. The collection includes great classical literature and more recent works where the U.S. copyright has expired. These books are yours to read and use without restrictions.


The Library of History by Diodorus the Sicilian is one of the most highly regarded universal histories in antiquities. His work includes the history of Egypt, Asia, Africa, Greece and Europe. His book is a must read for research of ancient history.


The Histories of Herodotus written in 440 BC is considered to be the founding work of history in Western literature. His history included stories and fables but he claimed to have traveled extensively and learned about many countries through direct observation.



chair

The thesis of Stolen Legacy is that the Egyptians created what is wrongly called Greek philosophy. Dr. James argues that the African origin of Greek Philosophy is well known but rarely discussed. Ancient Greek historians such as Herodotus and Diodorus the Sicilian wrote in significant detail about the contributions of Egypt. Egyptian technology and libraries were unmatched and Greek philosophers such as Pythagoras and Plato studied there. The contribution of Africa to the intellectual foundation of modern knowledge is tremendous but unacknowledged.



Bible Study The King James Bible (kjv), World English Bible (web) and Bible in Basic English (bbe) are all examples of public domain books. The King James Bible (kjv) online uses the content from these books and open source software to enhance Bible study capabilities. The site includes the verse of the day, search tools, christian literature and links to related content. It demonstrates the use of open source to create a valuable service.




Free Software


Free Software provides computer programs and capabilities at no cost but more importantly, it provides the freedom to run, edit, contribute to, and share the software. The importance of free software is a matter of access, not price. Software at no cost is a benefit but ownership rights to the software and source code is far more significant.


Free Office Software - The Libre Office suite provides top desktop productivity tools for free. This includes, a word processor, spreadsheet, presentation engine, drawing and flowcharting, database and math applications. Libre Office is available for Linux or Windows.


study

Linux is an open source computer operating system (OS) used on laptops, games, watches and super computers. The software and the source code used for Linux are both available to you at no cost. Use this powerful resource to your advantage.


Source Code - Want to change a program or know how it works? Open Source provides the source code for its programs so that anyone can use, modify or learn how to write those programs themselves. Visit the GNU source code repositories to download the source.




Educational Materials


Study at Harvard, Stanford or MIT - Open edX provides free online courses from Harvard, MIT, Columbia, UC Berkeley and other top Universities. Hundreds of courses for almost all major subjects and course levels. Open edx also offers some paid courses and selected certifications.


Linux Manual Pages - A man or manual page is a form of software documentation found on Linux/Unix operating systems. Topics covered include computer programs (including library and system calls), formal standards and conventions, and even abstract concepts.