Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

Ubuntu

Help File
Subramani M

 UsingTheTerminal
Contents

1. Why use the command-line?


2. Using this page
3. Starting a Terminal
1. In Gnome (Ubuntu)
2. In Xfce (Xubuntu)
3. In KDE (Kubuntu)
4. In LXDE (Lubuntu)
4. Commands
1. sudo: Executing Commands with
Elevated Privileges
2. File & Directory Commands
3. System Information Commands
4. Adding A New User
5. Options
6. "Man" and getting help
1. Searching for man files
7. Other Useful Things
1. Prettier Manual Pages
2. Pasting in commands
3. Save on typing
4. Change the text
8. More ways to run a terminal
9. More Information

Why use the command-line?


"Under Linux there are GUIs (graphical user interfaces), where you can point and click and drag,
and hopefully get work done without first reading lots of documentation. The traditional Unix
environment is a CLI (command line interface), where you type commands to tell the computer what
to do. That is faster and more powerful, but requires finding out what the commands are." 
-- from man intro(1)

There are many varieties of Linux, but almost all of them use similar commands that can be entered
from a command-line interface terminal.

There are also many graphical user interfaces (GUIs), but each of them works differently and there
is little standardization between them. Experienced users who work with many different Linux
distributions therefore find it easier to learn commands that can be used in all varieties of Ubuntu
and, indeed, in other Linux distributions as well.

1
Ubuntu
Help File
Subramani M

For the novice, commands-line interface commands can appear daunting:

sudo gobbledegook blah_blah -w -t -f aWkward/ComBinationOf/mixedCase/underscores_strokes/and.dots

However, it is important to note that even experienced users often cut and paste commands (from a
guide or manual) into the command-line terminal; they do not memorize them.

It is important, of course, to know how to use the command-line terminal - and anyone who can
manage typing, backspacing, and cutting and pasting can manage the command-line terminal (it is
not more difficult than that).

This page will outline a few crafty shortcuts which can make using a command-line interface easier.

Using this page


 All command names will be in bold.
 Commands needing to be typed will be in "bold with quotes".
 All of the commands on this page are to be issued from a command prompt in a terminal.
 Note that the terminal is case sensitive. User, user, and USER are all different to Linux.
Starting a Terminal
In Gnome (Ubuntu)

The terminal can be found at Applications menu -> Accessories -> Terminal.

In Xfce (Xubuntu)

The terminal can be found at Applications menu -> System -> Terminal.

In KDE (Kubuntu)

The terminal can be found at KMenu -> System -> Terminal Program (Konsole).

In LXDE (Lubuntu)

The terminal can be found at Menu -> Accessories -> LXTerminal.

Commands
sudo: Executing Commands with Elevated Privileges
 Most of the following commands will need to be prefaced with the sudo command. This
elevates privileges to the root-user administrative level temporarily, which is necessary when
working with directories or files not owned by your user account. When using sudo you will
be prompted for your password. Only users with sudo (administrative) privileges will be able
to use this command. (Please see RootSudo for more information on using sudo.)

2
Ubuntu
Help File
Subramani M

File & Directory Commands


 The tilde (~) symbol stands for your home directory. If you are user, then the tilde (~) stands
for /home/user
 pwd: The pwd command will allow you to know in which directory you're located
(pwd stands for "print working directory"). Example: "pwd" in the Desktop directory will show
"~/Desktop". Note that the Gnome Terminal also displays this information in the title bar of its
window. A useful gnemonic is "present working directory."
 ls: The ls command will show you ('list') the files in your current directory. Used with certain
options, you can see sizes of files, when files were made, and permissions of files.
Example: "ls ~" will show you the files that are in your home directory.
 cd: The cd command will allow you to change directories. When you open a terminal you will
be in your home directory. To move around the file system you will use cd. Examples:
o To navigate into the root directory, use "cd /"
o To navigate to your home directory, use "cd" or "cd ~"
o To navigate up one directory level, use "cd .."
o To navigate to the previous directory (or back), use "cd -"
o To navigate through multiple levels of directory at once, specify the full directory path
that you want to go to. For example, use, "cd /var/www" to go directly to the /www
subdirectory of /var/. As another example, "cd ~/Desktop"will move you to the
Desktop subdirectory inside your home directory.
 cp: The cp command will make a copy of a file for you. Example: "cp file foo" will make a
exact copy of "file" and name it "foo", but the file "file" will still be there. If you are copying a
directory, you must use "cp -r directory foo" (copy recursively). (To understand what
"recursively" means, think of it this way: to copy the directory and all its files and
subdirectories and all their files and subdirectories of the subdirectories and all their files,
and on and on, "recursively")
 mv: The mv command will move a file to a different location or will rename a file. Examples
are as follows: "mv file foo" will rename the file "file" to "foo". "mv foo ~/Desktop" will
move the file "foo" to your Desktop directory but will not rename it. You must specify a new
file name to rename a file.
o To save on typing, you can substitute '~' in place of the home directory.
o Note that if you are using mv with sudo you can use the ~ shortcut, because the
terminal expands the ~ to your home directory. However, when you open a root shell
with sudo -i or sudo -s, ~ will refer to the root account's home directory, not your
own.
 rm: Use this command to remove or delete a file in your directory.
 rmdir: The rmdir command will delete an empty directory. To delete a directory and all of its
contents recursively, use rm -r instead.
 mkdir: The mkdir command will allow you to create directories. Example: "mkdir
music" will create a directory called "music".
 man: The man command is used to show you the manual of other commands. Try "man
man" to get the man page forman itself. See the "Man & Getting Help" section down the
page for more information.

3
Ubuntu
Help File
Subramani M

System Information Commands


 df: The df command displays filesystem disk space usage for all mounted partitions. "df -h"
is probably the most useful - it uses megabytes (M) and gigabytes (G) instead of blocks to
report. (-h means "human-readable")
 du: The du command displays the disk usage for a directory. It can either display the space
used for all subdirectories or the total for the directory you run it on. Example:
user@users-desktop:~$ du /media/floppy
1032 /media/floppy/files
1036 /media/floppy/
user@users-desktop:~$ du -sh /media/floppy
1.1M /media/floppy/

 -s means "Summary" and -h means "Human Readable"


 free: The free command displays the amount of free and used memory in the system. "free
-m" will give the information using megabytes, which is probably most useful for current
computers.
 top: The top command displays information on your Linux system, running processes and
system resources, including CPU, RAM & swap usage and total number of tasks being run.
To exit top, press "q".
 uname -a: The uname command with the -a option prints all system information, including
machine name, kernel name & version, and a few other details. Most useful for checking
which kernel you're using.
 lsb_release -a: The lsb_release command with the -a option prints version information for
the Linux release you're running, for example:
user@computer:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 6.06 LTS
Release: 6.06
Codename: dapper

 ifconfig reports on your system's network interfaces.


Adding A New User
 "adduser newuser" command will create a new general user called "newuser" on your
system, and to assign a password for the newuser account use "passwd newuser".
Options
The default behaviour for a command may usually be modified by adding a --option to the
command. The ls command for example has an -s option so that "ls -s" will include file sizes in the
listing. There is also a -h option to get those sizes in a "human readable" format.

Options can be grouped in clusters so "ls -sh" is exactly the same command as "ls -s -h". Most
options have a long version, prefixed with two dashes instead of one, so even "ls --size --human-
readable" is the same command.

4
Ubuntu
Help File
Subramani M

"Man" and getting help

 man command, info command and command --help are the most important tools at the


command line.

Nearly every command and application in Linux will have a man (manual) file, so finding them is as
simple as typing "man "command"" to bring up a longer manual entry for the specified command.
For example, "man mv" will bring up the mv (Move) manual.

Move up and down the man file with the arrow keys, and quit back to the command prompt with "q".

"man man" will bring up the manual entry for the man command, which is a good place to start!

"man intro" is especially useful - it displays the "Introduction to user commands" which is a well-
written, fairly brief introduction to the Linux command line.

There are also info pages, which are generally more in-depth than man pages. Try "info info" for
the introduction to info pages.

Some software developers prefer info to man (for instance, GNU developers), so if you find a very
widely used command or app that doesn't have a man page, it's worth checking for an info page.

Virtually all commands understand the -h (or --help) option which will produce a short usage
description of the command and it's options, then exit back to the command prompt. Try "man
-h" or "man --help" to see this in action.

Caveat: It's possible (but rare) that a program doesn't understand the -h option to mean help. For
this reason, check for a man orinfo page first, and try the long option --help before -h.

Searching for man files

If you aren't sure which command or application you need to use, you can try searching the man
files.

 man -k foo will search the man files for foo. Try "man -k nautilus" to see how this works.
o Note that this is the same as doing apropos command.
 man -f foo searches only the titles of your system's man files. Try "man -f gnome", for
example.
o Note that this is the same as doing whatis command.
Other Useful Things
Prettier Manual Pages

Users who have Konqueror installed will be pleased to find they can read and search man pages in
a web browser context, prettified with their chosen desktop fonts and a little colour, by

5
Ubuntu
Help File
Subramani M

visiting man:/command in Konqueror's address bar. Some people might find this lightens the load if
there's lots of documentation to read/search.

Pasting in commands

Often, you will be referred to instructions that require commands to be pasted into the terminal. You
might be wondering why the text you've copied from a web page using ctrl+C won't paste in
with ctrl+V. Surely you don't have to type in all those nasty commands and filenames?
Relax. ctrl+shift+V pastes into a Gnome terminal; you can also do Middle Button Click on your
mouse (both buttons simultaneously on a two-button mouse) or Right Click and select Paste from
the menu. However, if you want to avoid the mouse and yet paste it, use "Shift+Insert", to paste the
command. If you have to copy it from another terminal / webpage, you can use "Ctrl+Insert" to copy.

Save on typing
Up
Scrolls through the commands you've entered previously.
Arroworctrl+p
Down
Takes you back to a more recent command.
Arroworctrl+n
Enter When you have the command you want.
A very useful feature. It autocompletes any commands or filenames, if there's
tab
only one option, or else gives you a list of options.
Searches for commands you've already typed. When you have entered a very
long, complex command and need to repeat it, using this key combination and
ctrl+r
then typing a portion of the command will search through your command
history. When you find it, simply press Enter.
The history command shows a very long list of commands that you have
typed. Each command is displayed next to a number. You can type !x to
History execute a previously typed command from the list (replace the X with a
number). If youhistory output is too long, then use history | less for a
scrollable list.
Change the text

The mouse won't work. Use the Left/Right arrow keys to move around the line.

When the cursor is where you want it in the line, typing inserts text - ie it doesn't overtype what's
already there.

ctrl+a or Hom
Moves the cursor to the start of a line.
e
ctrl+e or End Moves the cursor to the end of a line.

6
Ubuntu
Help File
Subramani M

ctrl+b Moves to the beginning of the previous or current word.


ctrl+k Deletes from the current cursor position to the end of the line.
ctrl+u Deletes the whole of the current line.
ctrl+w Deletes the word before the cursor.
More ways to run a terminal
You can also get it with a function key

You can run more than one - in tabs or separate windows

7
Ubuntu
Help File
Subramani M

 AptGet Howto
 This article applies to all supported versions of Ubuntu

Package management with APT


Contents

1. Package management with APT


1. Introduction to APT
2. Commands
1. Installation commands
1. auto-apt
2. Maintenance commands
3. Removal commands
4. Search commands
3. Typical usage example
4. Setting up apt-get to use a http-
proxy
1. Temporary proxy session
2. APT configuration file
method
3. BASH rc method
4. How to login a proxy user
5. Useful additional packages
6. See also
7. Additional links
8. Troubleshooting apt-get or
aptitude or Synaptic package
manager errors

 Package management via apt-get runs hand-in-hand with the/etc/apt/sources.list file. For


information on editing or updating your sources list see SourcesList.

Introduction to APT
"In the beginning there was the .tar.gz. Users had to compile each program that they wanted to use
on their GNU/Linux systems. When Debian was created, it was deemed necessary that the system

8
Ubuntu
Help File
Subramani M

include a method of managing the packages installed on the machine. The name dpkg was given to
this system. Thus the famous 'package' first came into being on GNU/Linux, a while before Red Hat
decided to create their own 'rpm' system.

A new dilemma quickly took hold of the minds of the makers of GNU/Linux. They needed a rapid,
practical, and efficient way to install packages that would manage dependencies automatically and
take care of their configuration files while upgrading. Here again, Debian led the way and gave birth
to APT, the Advanced Packaging Tool, which has since been ported by Conectiva for use with rpm
and has been adopted by some other distributions."

 -- From Debian APT HOWTO

Commands

 All of these commands must be run as root or with superuser privileges, see sudo for more
information. Replace <package_name> with the name of the package you are attempting to
install.


sudo apt-get install ubuntu-desktop
Installation commands
 apt-get install <package_name>

This command installs a new package.

 apt-get build-dep <package_name>


This command searches the repositories and installs the build dependencies for
<package_name>. If the package is not in the repositories it will return an error.
 aptitude install <package_name>
Aptitude is a [http://en.wikipedia.org/wiki/Ncurses Ncurses] viewer of packages installed or
available. Aptitude can be used from the command line in a similar way to apt-get.
See man aptitude for more information.

 APT and aptitude will accept multiple package names as a space delimited list. For example:

apt-get install <package1_name> <package2_name> <package3_name>

9
Ubuntu
Help File
Subramani M

 Use the -s flag to simulate an action."sudo apt-get -s install <package_name>"


will simulate installing the package showing you what packages will be installed and
configured.
auto-apt
 auto-apt run <command_string>
When invoked, the auto-apt command automatically installs packages upon missing file
access. If a program tries to access a file known to belong in an uninstalled package, auto-
apt will install that package using apt-get. This feature requires aptand sudo to work.

 Auto-apt keeps databases which need to be kept up-to-date in order for it to be effective.
This is achieved by calling the commands auto-apt update, auto-apt updatedb and auto-apt
update-local.
 Usage example

o  You're compiling a program and, all of a sudden, there's an error because it


needs a file you don't have. The program auto-apt asks you to install packages if
they're needed, stopping the relevant process and continuing once the package is
installed.
# auto-apt run ./configure

It will then ask to install the needed packages and call apt-get automatically. If you're
running X, a graphical interface will replace the default text interface.

Maintenance commands
 apt-get update
Run this command after changing /etc/apt/sources.list or /etc/apt/preferences . For
information regarding/etc/apt/preferences, see PinningHowto. Run this command periodically
to make sure your source list is up-to-date. This is the equivalent of "Reload" in Synaptic or
"Fetch updates" in Adept.
 apt-get upgrade

This command upgrades all installed packages. This is the equivalent of "Mark all upgrades"
in Synaptic.

 apt-get dist-upgrade

10
Ubuntu
Help File
Subramani M

The same as the above, except add the "smart upgrade" checkbox. It tells APT to use
"smart" conflict resolution system, and it will attempt to upgrade the most important packages
at the expense of less important ones if necessary.

 "apt-get dist-upgrade" does not perform distribution upgrade. See


[http://www.ubuntu.com/getubuntu/upgradingupgrading] for more information.
 apt-get check

This command is a diagnostic tool. It does an update of the package lists and checks for
broken dependencies.

 apt-get -f install
This command does the same thing as Edit->Fix Broken Packages in Synaptic. Do this if
you get complaints about packages with "unmet dependences".
 apt-get autoclean
This command removes .deb files for packages that are no longer installed on your system.
Depending on your installation habits, removing these files from /var/cache/apt/archives may
regain a significant amount of diskspace.
 apt-get clean
The same as above, except it removes all packages from the package cache. This may not
be desirable if you have a slow internet connection, since it will cause you to redownload any
packages you need to install a program.
o The package cache is in /var/cache/apt/archives . The command
du -sh /var/cache/apt/archives

will tell you how much space cached packages are consuming.

 dpkg-reconfigure <package_name>

Reconfigure the named package. With many packages, you’ll be prompted with some
configuration questions you may not have known were there.

o  For example:
dpkg-reconfigure fontconfig-config

11
Ubuntu
Help File
Subramani M

will present you with a "wizard" on configuring fonts in Ubuntu.

 echo "<package_name> hold" | dpkg --set-selections


This command places the desired package on hold. This is the same as
Synaptic's Package->Lock Version.

 This command may have the unintended side effect of preventing upgrades
to packages that depend on updated versions of the pinned package. apt-
get dist-upgrade will override this, but will warn you first. If you want to use
this command with sudo, you need to
use echo "<package_name> hold" | sudo dpkg --set-selections notsudo 
echo "<package_name> hold" | dpkg --set-selections.

 echo "<package_name> install" | dpkg --set-selections

This command removes the "hold" or "locked package" state set by the above command.
The note above about sudo usage applies to this command.

Removal commands
 apt-get remove <package_name>

This command removes an installed package, leaving configuration files intact.

 apt-get purge <package_name>

This command completely removes a package and the associated configuration files.
Configuration files residing in ~ are not usually affected by this command.

o + operator

  If you want to remove package1 and install package2 in one step:
apt-get purge remove <package1> <package2>+

12
Ubuntu
Help File
Subramani M

 apt-get autoremove

This command removes packages that were installed by other packages and are no longer
needed.

o apt-get autoremove <package_name>

This command removes an installed package and dependencies.

Search commands
 apt-cache search <search_term>
This command will find packages that include <search_term>.
 dpkg -l *<search_term>*
This will find packages whose names contain <search_term>. Similar to apt-
cache search, but also shows whether a package is installed on your system by marking it
with ii (installed) and un (not installed).
 apt-cache show <package_name>
This command shows the description of package <package_name> and other relevant
information including version, size, dependencies and conflicts.
 dpkg --print-avail <package_name>

This command is similar to "apt-cache show".

 dpkg -L <package_name>
This command will list files in package <package_name>.
 dpkg -c foo.deb
This command lists files in the package "foo.deb". Note that foo.deb is a pathname. Use this
command on .deb packages that you have manually downloaded.
 dlocate <package_name>
This command determines which installed package owns <package_name>. It shows files
from installed packages that match <package_name>, with the name of the package they
came from. Consider this to be a "reverse lookup" utility.

 In order to use this command, the package dlocate must be installed on your


system.

13
Ubuntu
Help File
Subramani M

 dpkg -S <package_name>
This command does the same as dlocate, but does not require the installation of any
additional packages. It is slower than dlocate but has the advantage of being installed by
default on all Debian and Ubuntu systems.
 apt-file search <package_name>

This command acts like dlocate and dpkg -S, but searches all available packages. It answers
the question, "what package provides this file?".

o apt-file needs to be updated regularly like apt-get. Use the command:


apt-file update

 In order to use this command, the package apt-file must be installed on your


system.
 apt-cache pkgnames

This command provides a listing of every package in the system

 A general note on searching: If searching for a generates a list that is too long, you can filter
your results by piping them through the command grep. Examples:
o apt-cache search filename | grep -w filename

will show only the files that contain filename as a whole word

o dpkg -L package | grep /usr/bin

will list files located in the directory /usr/bin, useful if you're looking for a particular
executable.

For more information on apt-get, apt-cache and dpkg consult their manual pages by using
the man command. These manuals will provide a wider scope of information in addition to all of the
options that you can use with each program.

  Example:
man apt-get

14
Ubuntu
Help File
Subramani M

Typical usage example


I want to feel the wind in my hair, I want the adrenaline of speed. So lets install a racing game. But
what racing games are available?

apt-cache search racing game

It gives me a lot of answers. I see a game named "torcs". Lets get some more information on this
game.

apt-cache show torcs

Hmmm... it seems interesting. But is this game not already installed on my computer? And what is
the available version? Is it from Universe or main?

apt-cache policy torcs

Ok, so now, let's install it!

apt-get install torcs

What is the command I must type in the console to launch this game? In this example, it's
straightforward ("torcs"), but that's not always the case. One way of finding the name of the binary is
to look at what files the package has installed in "/usr/bin". For games, the binary will be in
"/usr/games". For administrative programs, it's in "/usr/sbin".

dpkg -L torcs | grep /usr/games/

The first part of the command display all files installed by the package "torcs" (try it). With the second
part, we ask to only display lines containing "/usr/games/".

Hmmm, that game is cool. Maybe there are some extra tracks?

apt-cache search torcs

But I'm running out of space. I will delete the apt cache!

apt-get clean

15
Ubuntu
Help File
Subramani M

Oh no, my mother asked me to remove all games from this computer. But I want to keep the
configuration files so I can simply re-install it later.

apt-get remove torcs

If I want to also remove config files :

apt-get purge torcs


Setting up apt-get to use a http-proxy
These are three methods of using apt-get with a http-proxy.

Temporary proxy session

This is a temporary method that you can manually use each time you want to use apt-get through a
http-proxy. This method is useful if you only want to temporarily use a http-proxy.

Enter this line in the terminal prior to using apt-get (substitute your details for yourproxyaddress and
proxyport).

export http_proxy=http://yourproxyaddress:proxyport
APT configuration file method

This method uses the apt.conf file which is found in your /etc/apt/ directory. This method is useful if
you only want apt-get (and not other applications) to use a http-proxy permanently.

 On some installations there will be no apt-conf file set up. This procedure will either edit
an existing apt-conf file or create a new apt-conf file.
gksudo gedit /etc/apt/apt.conf

Add this line to your /etc/apt/apt.conf file (substitute your details for yourproxyaddress and
proxyport).

Acquire::http::Proxy "http://yourproxyaddress:proxyport";

Save the apt.conf file.

BASH rc method

16
Ubuntu
Help File
Subramani M

This method adds a two lines to your .bashrc file in your $HOME directory. This method is useful if
you would like apt-get and other applications for instance wget, to use a http-proxy.

gedit ~/.bashrc

Add these lines to the bottom of your ~/.bashrc file (substitute your details for yourproxyaddress and
proxyport)

http_proxy=http://yourproxyaddress:proxyport
export http_proxy

Save the file. Close your terminal window and then open another terminal window or source
the ~/.bashrc file:

source ~/.bashrc

Test your proxy with sudo apt-get update and whatever networking tool you desire. You can use
firestarter or conky to see active connections.

If you make a mistake and go back to edit the file again, you can close the terminal and reopen it or
you can source ~/.bashrc as shown above.

source ~/.bashrc
How to login a proxy user

If you need to login to the Proxy server this can be achieved in most cases by using the following
layout in specifying the proxy address in http-proxy. (substitute your details for username, password,
yourproxyaddress and proxyport)

http_proxy=http://username:password@yourproxyaddress:proxyport
Useful additional packages
 Deborphan
 Debfoster

17
Ubuntu
Help File
Subramani M

 grep
What Is grep?
Grep is a command line tool that allows you to find a string in a file or stream. It can be used with
Regular expression to be more flexible at finding strings.

How To Use grep


In the simplest case, grep can simply be invoked like this :

% grep 'STRING' filename

This is OK but it does not show the true power of grep. First this only looks at one file. A cool
example of using grep with multiple file would be to find all files in a directory that contains the name
of a person. This can be easily accomplished using a grep in the following way :

% grep 'Nicolas Kassis' *

Notice the use of single quotes; the quotes are not essential, but in this example they are required
because the name contains a space. Double quotes could also have been used in this example.

Now lets use some regular expressions...

Grep Regular Expression


grep can search for complicated patterns to find what you need. Here is a list of some of the special
characters used to create a regular expression:

Grep Regular Expression

^ Denotes the beginning of a line

$ Denotes the end of a line

. Matches any one characters

18
Ubuntu
Help File
Subramani M

* Matches 0 or more of the previous characters

.* Matches any number or type of characters

[] Matches on character for the one listed in the the Square brackets

[^] Does not match any characters listed

\<, \> Denotes the beginning and end (respectively) of a word

So an example of a regular expression search would be

% grep "\<[A-Za-z].*" file

This will search for any word which begins with a letter upper or lower case.

For more details check:

 BasicCommands
 http://www.gnu.org/software/emacs/manual/html_node/emacs/Grep-Searching.html
 http://en.wikipedia.org/wiki/Grep
 man grep and info grep on your computer

19
Ubuntu
Help File
Subramani M

 find

Contents

1. Introduction
2. The Basics
1. Locating Files by Name
2. Locating Files by Size
3. Locating Files by Access Time
3. Advanced Usage
1. Combining Searches
2. Acting On The files
3. Using xargs
4. More Information

Introduction
The GNU find command search files within within a directory and its subdirectories according to
several criteria such as name, size and time of last read/write. By default find prints the name of the
located files but it can also perform commands on these files.

The GNU find command is part of the GNU findutils and is installed on every Ubuntu system.
findutils is actually made up of 4 utilities:

1. find - search for files in a directory hierarchy


2. locate - list files in databases that match a pattern
3. updatedb - update a file name database
4. xargs - build and execute command lines from standard input

This wiki page will be only be dealing with find while also briefly mentioning xargs. Hopefully locate
and updatedb will be covered on their own page in the near future.

20
Ubuntu
Help File
Subramani M

The Basics
The syntax for using find is:

find [-H] [-L] [-P] [path...] [expression]

The 3 options [-H] [-L] [-P] are not commonly seen but should at least be noted if only to realise that
the -P option will be thedefault unless another option is specified:

 -H : Do not follow symbolic links, except while processing the command line arguments.
 -L : Follow symbolic links.
 -P : Never follow symbolic links: the default option.

The option [path...] refers to the particular location that you wish to search, whether it be your
$HOME directory, a particular directory such as /usr, your present working directory which can
simply be expressed as '.' or your entire computer which can be expressed as '/'.

The option [expression] refers to one or a series of options which effect the overall option of the find
command. These options can involve a search by name, by size, by access time or can also involve
actions taken upon these files.

Locating Files by Name


The most common use of find is in the search for a specific file by use of its name. The following
command searches the home directory and all of its subdirectories looking for the file mysong.ogg:

find $HOME -name 'mysong.ogg'

It is important to get into the habit of quoting patterns in your search as seen above or your search
results can be a little unpredictable. Such a search can be much more sophisticated though. For
example if you wished to search for all of the ogg files in your home directory, some of which you
think might be named 'OGG' rather than 'ogg', you would run:

find $HOME -iname '*.ogg'

Here the option '-iname' performs a case-insensitive search while the wildcard character '*' matches
any character, or number of characters, or zero characters. To perform the same search on
your entire drive you would run:

sudo find / -iname '*.ogg'

This could be a slow search depending on the number of directories, sub-directories and files on
your system. This highlights an important difference in the way that find operates in that it examines

21
Ubuntu
Help File
Subramani M

the system directly each time unlike programs like locate or slocate which actually examine a
regularly updated database of filnames and locations.

Locating Files by Size


Another possible search is to search for files by size. To demonstrate this we can again search the
home directory for Ogg Vorbis files but this time looking for those that are 100 megabytes or larger:

find $HOME -iname '*.ogg' -size +100M

There are several options with -size, I have used 'M' for 'megabytes' here but 'k' for 'kilobytes' can be
used or 'G' for 'Gigabytes'. This search can then be altered to look for files only that are less than
100 megabytes:

find $HOME -iname '*.ogg' -type f -size -100M

Are you starting to see the power of find, and the thought involved in constructing a focused search?
If you are interested there is more discussion of these combined searches in the Advanced Usage
section below.

Locating Files by Access Time


It is also possible to locate files based on their access time or the time that they were last used, or
viewed by the system. For example to show all files that have not been accessed in the $HOME
directory for 30 days or more:

find $HOME -atime +30

This type of search is normally more useful when combined with other find searches. For example
one could search for all ogg files in the $HOME directory that have an access time of greater than 30
days:

find $HOME -iname '*.ogg' -atime +30

The syntax works from left to right and by default find joins the 2 expressions with an implied "and".
This is dealt with in more depth in the section below entitled "Combining Searches".

Advanced Usage
The sections above detail the most common usage of find and this would be enough for most
searches. However there are many more possibilities in the usage of find for quite advanced
searches and this sections discusses a few of these possibilities.

22
Ubuntu
Help File
Subramani M

Combining Searches
It is possible to combine searches when using find with the use of what is known in the find man
pages as operators. The classic example is the use of a logical AND syntax:

find $HOME -iname '*.ogg' -size +20M

This find search performs initially a case insensitive search for all the ogg files in your $HOME
directory and for every true results it then searches for those with a size of 20 megabytes and over.
This contains and implied operator which could be written joined with an -a. This search can be
altered slightly by use of an exclamation point to signify negation of the result:

find $HOME -iname '*.ogg' ! -size +20M

This performs the same search as before but will look for ogg files that are not greater than 20
megabytes. It is possible also to use a logical OR in your find search:

find $HOME -iname '*.ogg' -o -iname '*.mp3'

This will perform a case insensitive search in the $HOME directories and find all files that are either
ogg OR mp3 files. There is great scope here for creating very complex and finely honed searches
and I would encourage a through reading of the find man pages searching for the topic
OPERATORS.

Acting On The files


One advanced but highly useful aspect of find usage is the ability to perform a user-specified action
on the result of a find search. For example the following search looks for all ogg vorbis files in the
$HOME directory and then uses -exec to pass the result to the du program to give the size of each
file:

find $HOME -name '*.ogg' -type f -exec du -h '{}' \;

This syntax is often used to delete files by using -exec rm -rf but this must be used with great
caution, if at all, as recovery of any deleted files can be quite difficult.

Using xargs
When using a really complex search it is often a good idea to use another member of the findutils
package: xargs. Without its use the message Argument list too long could be seen signalling that the
kernel limit on the combined length of a commandline and its environment variables has been
exceeded. xargs works by feeding the results of the search to the subsequent command in batches
calculated on the system capabilities (based on ARG_MAX). An example:

23
Ubuntu
Help File
Subramani M

find /tmp -iname '*.mp3' -print0 | xargs -0 rm

This example searches the /tmp folder for all mp3 files and then deletes them. You will note the use
of both -print0 and xargs -0which is a deliberate strategy to avoid problems with spaces and/or
newlines in the filenames. Modern kernels do not have the ARG_MAX limitation but to keep your
searches portable it is an excellent idea to use xargs in complex searches with subsequent
commands.

More Information
 Linux Basics: A gentle introduction to 'find' - An Ubuntu Forums guide that was incorporated
into this wiki article with the gracious permission of its author.
 Using Find - Greg's Wiki - A very comprehensive guide to using find, along similar lines to
this guide, that is well worth reading through.
 Linux Tutorial: The Power of the Linux Find Command The amazing Nixie Pixel gives a video
demonstration of find.

24
Ubuntu
Help File
Subramani M

 CommandlineHowto
Contents

1. Introduction
1. What is it?
2. History
1. POSIX
3. Advantages of using the command
line
4. Prerequisites
5. How to invoke it
6. Basic structure and concepts
2. Command Syntax
1. Single Command
2. Multiple Commands
3. Wildcards
1. Specifing a single character
2. Specifying multiple
characters
3. Specifying a range
4. Control Flow
1. Redirection
2. Pipe
3. Further reading

Introduction
Even though Ubuntu is the newbie friendly and polished graphical distribution, there are still
situations where a significant amount of time and mouse-clicking can be spared by typing a bit. I
don't think this is a bad thing at all; no matter what you do, Linux has one of its real strengths in the
Command Line! 

What is it?
25
Ubuntu
Help File
Subramani M

A Command Line is, in all simplicity, a user interface based on lines of commands. You can say that
it is a textual direct serial processor. Most commonly, the user interacts directly with the computer
by typing one line (although it can be more than one), which triggers actions from the computer
based on the syntax of the current processor.
Before everything gets too complicated, we can quite simply move on.  The impatient can move
right on to the Command Syntax section.

History
In the early days of computers, there was only the Command Line. The concept of a Graphical User
Interface (GUI) after which most GUI are modeled was developed by engineers at Xerox's Palo
Alto Research Center (PARC). A bit later, Apple paid a whole bunch of money to be allowed to
"study" their GUI idea. And, after a while, Apple had their own GUI.

Not until 1986 did UNIX get its first GUI, developed by the MIT Project. They named it X. Linux,
however, had to wait ten more years before XFree86 was released. XFree86 was, and is even
today, a free adaptation of the original X server.

As mentioned earlier, the CLI (Command Line Interface) was the only way to communicate with
computers before the GUI was invented. In 1969, Bell Telephone Laboratories released V1 of the
UNIX Timeshare System. UNIX had a shell called sh, which was the only means of communicating
with the computer, and it would stay that way for quite some time.

Later on, there came derivatives of UNIX: HP-UX, 1BSD, Solaris, OpenVMS, IRIX, SCO XENIX, etc.
As time progressed, GNU/Linux emerged. However, the history of Linux itself is way off the scope of
this HOWTO. Suffice to say that alternative CLI to sh emerged: zsh, ksh, bourne shell, etc.

POSIX

The Wikipedia defines POSIX as the following:

"POSIX is the collective name of a family of related standards specified by the IEEE to define the
application program interface (API) for software designed to run on variants of the Unix OS. They
are formally designated as IEEE 1003 and the international standard name is ISO/IEC 9945. The
standards emerged from a project, begun circa 1985. The term POSIX was suggested by Richard
Stallman in response to an IEEE request for a memorable name; before that the standards effort
was called IEEE-IX. POSIX is a near acronym for Portable Operating System Interface, with the X
signifying the Unix heritage of the API."

This sounds fancy and all, but to stay rather concise, POSIX is the underlying standard and
functionality of how your CLI responds.

Advantages of using the command line


So this all sounds very dull and boring, not to mention hard.
Well, it isn't, really.   It's quite easy once you understand the basics.

26
Ubuntu
Help File
Subramani M

Some advantage of using the command line are:

 save you time.


 can help when you are unable to use the GUI, such as a system crash or a configuration
issue.
 enable you to use Linux in ways that using a GUI exclusively can not.

For example, you have been called by the systems administrator that you have used too much
space. You want to quickly work out where the most space is used, so using a graphical interface,
start your timer - go. Now, go to a command line and type: du | sort -n (we will describe more
later). See? It is faster to do some things on the command line (and other times, easier for
graphical).

Prerequisites
This assumes that you are running any version of Ubuntu Linux and have a desire to learn its inner
workings.

How to invoke it
For the purpose of this document, we will invoke the command line interface from the Desktop.

Ubuntu
Applications | Accessories | Terminal

Kubuntu
KDE Menu | System | Konsole Terminal Program

Xubuntu 6.10
Applications | System | Terminal

An alternative way to invoke the command line, only using keyboard shortcuts (since on the
command line, you would mostly be interacting only through the keyboard) is:

On GNOME (Ubuntu): Alt + F2 -> (Type within the text box) gnome-terminal (Press return) 


On KDE (Kubuntu): Alt + F2 -> (Type within the text box) konsole (Press return) 

Basic structure and concepts

27
Ubuntu
Help File
Subramani M

The first thing that you should notice is something like:

dud@shadowplay:~ $
or
[dud@shadowplay ~]$

What you see here is called the prompt. It signifies that the computer is ready and awaiting user
input. In my case, dud is the user that I'm logged in as. shadowplay is the computer's hostname,
and ~ is the current directory (the user's home directory).

Concepts:

 A terminal is a "physical"(direct) interface to your Linux Operating System.


 A terminal emulator is what we'll be using here. This is a CLI wrapped within your running
GUI. Any applications running in a terminal emulator will be killed if you close the terminal
emulator.
 A shell is an interpreter for your terminal.
 A command is usually a small utility that the shell will execute for you.
 Output is what a command returns; most often this is returned on the terminal.
 Input is the arguments or data that any given command will take. Input will change the way a
given command acts.
 A process is a running application on your computer. It can be active, sleeping, or in a
number of other states.

Command Syntax
This section will try to give you a good rundown of the basic usage for the bash shell, which is the
default user shell in Ubuntu.

Single Command
The command syntax will vary with each command. Here are some of the basics.

The simplest way to use some commands is to type just the command.

 command

Example:

dud@shadowplay:~ $ ls
file1.txt
file2.pdf
file3.mp3

28
Ubuntu
Help File
Subramani M

file1.pdf
another_file.txt
Yet-Another_file.txt
file-with_other-NAME.TXT

The above example displays the contents of the current working directory, while other commands
may require one or more arguments.

 command <argument>

Example:

dud@shadowplay:~ $ cat file1.txt


Roses are red.
Violets are blue,
and you have the bird-flu!

The above example shows you the content of the file1.txt file by adding the filename as the
argument for the cat command. Almost all commands, whether they have arguments or not, have
options.

 command -option

Example:

dud@shadowplay:~ $ ls -r
file-with_other-NAME.TXT
Yet-Another_file.txt
another_file.txt
file1.pdf
file3.mp3
file2.pdf
file1.txt

Using the previous example of showing the current directory, we have added the -r option. As you
can see, the listing of the current working directory has been displayed in the reverse order.

Multiple Commands
Sometimes the desired task may require the use of more than one command to be completed. Here
is the syntax for the use of multiple commands.

If you want to execute two commands consecutively, then you would use the following syntax:

 command1 ; command2

29
Ubuntu
Help File
Subramani M

Example:

dud@shadowplay:~ $grep red file1.txt ; grep blue file1.txt


Roses are red,
Violets are blue,

In the example above, command1 and command2 are executed. However, if you need command1
to complete successfully before executing command2, then you would use the following syntax:

 command1 && command2

Example:

dud@shadowplay:~ $ grep red file1.txt && grep blue file1.txt


Roses are red,
Violets are blue,
dud@shadowplay:~ $ grep purple file1.txt && grep blue file1.txt
dud@shadowplay:~ $

In the example above, you will notice nothing happened when the first command did not complete
successfully. If you want command2 to execute only if command1 fails, then you would use the
following syntax:

 command1 || command2

Example:

dud@shadowplay:~ $ grep red file1.txt || grep blue file1.txt


Roses are red,
dud@shadowplay:~ $ grep purple file1.txt || grep blue file1.txt
Violets are blue,
dud@shadowplay:~ $

In the example above, you will notice command2 was only executed when command1 failed.

Wildcards
Wildcards are a useful feature that allows an unknown value or values to be used with another
command. This becomes very useful with commands such as "ls" allowing only a range of filenames
to be displayed.

There are three operators used with wildcards - "*", "?" and "[x-y]".

Specifing a single character

30
Ubuntu
Help File
Subramani M

The "?" is used to represent a single unknown character, consider we have a folder containing four
files: file1.pdf, file2.pdf, file2.mp3 and file23.pdf. If wanted to know which PDF filenames contained
numbers, then we could use:

dud@shadowplay:~ $ ls file?.pdf
file1.pdf
file2.pdf
Specifying multiple characters

Using the same files as the previous example, if we wanted to search for all files called "file2" of any
type we could:

Example:

dud@shadowplay:~ $ ls file2.*
file2.pdf
file2.mp3
Specifying a range

If we wanted to know all PDF filenames beginning with "file" and a number between 1 and 5 then we
use:

dud@shadowplay:~ $ ls file[2-23].pdf
file2.pdf
file23.pdf
Control Flow
Commands read input from the keyboard (standard input, or stdin) and write to output (standard out,
or stdout). There is also a special output category for error messages called standard error (or
stderr). These three locations are created automatically for each program.

We can redirect input and output to and from a command.

Redirection

If you wanted the output of a command to go to a file instead of the terminal, then you would use the
following syntax:

 command > filename

Example:

dud@shadowplay:~ $ ls > file4.txt


dud@shadowplay:~ $ cat file4.txt

31
Ubuntu
Help File
Subramani M

file1.txt
file2.pdf
file3.mp3
file1.pdf
another_file.txt
Yet-Another_file.txt
file-with_other-NAME.TXT
file4.txt

The above example will create file4.txt if it is not found. NOTE: If file4.txt exists already, the above
command will overwrite its contents. If you want to add to the end of a existing file, then you would
use the following syntax:

 command >> filename

Example:

dud@shadowplay:~ $ ls >> file4.txt


dud@shadowplay:~ $ cat file4.txt
file1.txt
file2.pdf
file3.mp3
file1.pdf
another_file.txt
Yet-Another_file.txt
file-with_other-NAME.TXT
file4.txt
file1.txt
file2.pdf
file3.mp3
file1.pdf
another_file.txt
Yet-Another_file.txt
file-with_other-NAME.TXT
file4.txt

In the example, you will notice the file was appended with the new information. Now we are going to
do a different redirection: We are going to take the input from a file for the command to be executed.
Here is the syntax for this redirection:

 command < filename

Example:

dud@shadowplay:~ $ sort < file4.txt


another_file.txt
another_file.txt

32
Ubuntu
Help File
Subramani M

file1.txt
file1.txt
file2.pdf
file2.pdf
file3.mp3
file3.mp3
file4.txt
file4.txt
file-with_other-NAME.TXT
file-with_other-NAME.TXT
Yet-Another_file.txt
Yet-Another_file.txt

As you can see from this example, we used the file4.txt as input into the sort command.

Pipe

When you need the output from command 1 for the input into command 2, then you would use pipe
character '|'. Here is the syntax for the pipe character:

 command | command

Example:

dud@shadowplay:~ $ ls | sort
another_file.txt
file1.pdf
file1.txt
file2.pdf
file3.mp3
file-with_other-NAME.TXT
Yet-Another_file.txt

The above example is using the output from ls as input to the sort command. You will notice the list
has been sorted.

As you can see, the command line is an easy and powerful way of completing many tasks. If you
want more information on using the command line, then look at the further reading section of this
document.

Further reading
http://rute.2038bug.com/index.html.gz 
BasicCommands has a list of basic commands.
AdvancedCommandlineHowto has some advanced command line features such as scripting.

33
Ubuntu
Help File
Subramani M

 HowToReadline
Content Cleanup Required: This article should be cleaned-up to follow the content standards in
the Wiki Guide. More info...
Style Cleanup Required: This article does not follow the style standards in the Wiki Guide. More
info...

If you use a Bash shell, you might know it uses the Readline library for editing command lines. Many
other programs use it too.The Readline configuration supplied with Ubuntu and Kubuntu allows
you to use some obvious keys, such as the left/right arrow keys, for moving around and editing the
command line, but you might want a few features beyond those provided. In fact, Readline has a rich
set of default key bindings, but they can be difficult to remember or awkward to use. For instance,
<Alt>d deletes the word to the right of the cursor. Enter the Bash builtin command bind -P for a
complete list of the bindings.

This article describes how to add some keys and key combinations to the repertoire. A new Readline
configuration file is attached which defines the following keys:

<Ctrl><arrow> Move forwards and backwards a word at a time1


<Ctrl><Delete> Delete word to right of cursor
<Ctrl><Backspace> Delete word to left of cursor
<Shift><Delete> Delete from cursor to end of line
<Shift><Backspace> Delete from cursor to start of line
<Insert> Toggle overwrite/insert mode2

1
 This has been part of the default configuration since Kubuntu release 6.06, but is included here for
completeness. 
2
 Each call to Readline starts in insert mode; the Insert key doesn't "stick" between calls.

A word is defined by Readline to be a sequence of letters or numbers; it is not possible to change


this definition. Other parts of Ubuntu might define a word differently. For instance, Konsole by default
defines the characters in :@-./_~ to be part of a word when double clicking (see Settings/Configure
Konsole).

34
Ubuntu
Help File
Subramani M

Keyboard map

Before installing the new Readline configuration file, it is necessary to configure the terminal
emulator to emit a unique byte sequence for each required key combination. Konsole needs only a
small change: with the default XTerm (XFree 4.x.x)keyboard table, it emits the same byte
sequence for <Ctrl><Backspace> as for <Shift><Backspace>, which is just the same as for
<Backspace> on its own.

Attached to this article is myKubuntu.keytab, which configures Konsole to emit the required byte
sequences. The simplest way to install it is to put it in ~/.kde/share/apps/konsole (~ is
the conventional notation for "my home directory"). Alternatively, you could make a system-wide
change by putting the keytab in /usr/share/apps/konsole.

Rather than downloading the entire table, you could download the patch in default.keytab.patch and
apply it to the defaultkeyboard table. The default keyboard table doesn't exist as a .keytab file since
it's built into Konsole; instead, it's available
in/usr/share/doc/konsole/README.default.Keytab.gz. To create the new keytab, issue
these commands:

gzip -cd /usr/share/doc/konsole/README.default.Keytab.gz > myKubuntu.keytab


patch myKubuntu.keytab default.keytab.patch

After installing myKubuntu.keytab as outlined above, start a new Konsole session and


select Settings/Keyboard/XTerm (myKubuntu). If you're happy with this after testing,
select Settings/Save as Default.

If you don't use the default Konsole keyboard table, and need to modify a different keytab file, a
useful technique during development is to start Konsole with the command konsole --
keytab myKubuntu (or whatever name you choose). This allows you to see any error messages
from Konsole, for instance those that say a key combination has been defined earlier in the keytab
file. To verify a key combination, a useful technique is to start vim, enter Insert mode with i, and
enter <Ctrl>v followed by the key
combination. See /usr/share/doc/konsole/README.KeyTab for details of the format of the
keytab file.

[FIXME: not described are the GNOME terminal emulator, the Linux tty console, or classic xterm.]

Readline configuration

After your terminal emulator is configured to emit the required byte sequences, it's time to configure
Readline. Download the fileinputrc and install it either in your home directory as .inputrc or as a
replacement for the existing file /etc/inputrc.

Again, you might prefer to apply a patch instead of installing a complete replacement.


Download inputrc.patch (say, to /tmp) and with root privilege issue the command:

35
Ubuntu
Help File
Subramani M

patch --backup /etc/inputrc /tmp/inputrc.patch

Note this creates a backup file, most likely called /etc/inputrc.orig (see patch(1) for details).

Remember to start a new session before testing and, if necessary, change the keyboard table.

Other terminal emulators

The following line in /etc/inputrc makes the GNOME terminal emulator use <Ctrl><Delete> to delete
the word in front of the cursor:

"\e[3;5~": kill-word

However, I have not yet found a way to use <Ctrl><Backspace>.

Summary
You have modified your terminal emulator to emit the byte sequences required by your custom
Readline configuration file. Now Bash and other command-line programs can use the keys defined
in the table above, as well as Home, End, etc.

Related Pages
 GNU Readline Library
 Bash Reference Manual

36
Ubuntu
Help File
Subramani M

37

You might also like