www.ScienceOfAtomics.com/linux
Shell Commands
Using bash and the commandline

•  HOME  •  THEORY  •  PRACTICE  •    •  LOGIN  •  FORUM  •  CONTACT  • 

COMMANDLINE   CONVENTIONS

The word User when capitalized indicates the operator of a Linux PC Workstation or Computer having, at a minimum, a keyboard, a mouse, and a video screen as the interface for control of the computer. Standard operating protocol requires each User to validate a login sequence every time the machine is powered-up or rebooted. Even if autologin is used, a valid login sequence is still executed automatically.

The login name of root is reserved for use by the Root User or superuser, also called the supervisor or machine administrator. The Root User has unrestricted authority over all machine operations. All other Users operate within constraints determined by the Operating System under control of the Root User. Standard operating protocol reserves the Root login solely for administrative use, but allows any User knowing the Root password to switch to Root permissions at any time.

Login opens a software interface to the Operating System (OS) kernel via a shell. Most modern login shells immediately run a Graphical Video Interface (GVI) and enable an elementary Audio Interface. Many Users complete their Sessions entirely within the GVI and are often unaware of any alternative.

The Commandline Interface (CI) traditionally assumes a terminal comprised of keyboard input and video or printer output. Traditional video output is a text screen of eighty columns and twenty-five lines (80x25), the last of which can be a System Menu. Such a terminal is called a Console. A CI can be accessed from within a GVI using one of many Terminal Emulation programs such as xterm or rxvt.

A normal Linux log-in is to a command shell as an ordinary User. Because Linux is a full multiuser system, each User has a private home directory with the same name as the User's login – /home/john/ – in which are kept the User's personal settings and data files.

Each system has a single Root User with absolute control and unrestricted access permissions. The Root User's login name is rootand the home directory is /root/ The Root User is sometimes called the superuser, system administrator, or sysop.

All Linux systems contain copious documentation as part of a standard installation. However, much of this documentation is definitive, not explanatory; that is, it is designed to provide concise basic information for technically competent Users. A large amount of explanatory information is also available, but not always installed. All of this is available on the Internet free of charge.

Most Linux documentation follows well-defined traditions, conventions, and standards that, whilst often somewhat daunting at first blush, are soon understood and quickly become familiar. All English documentation uses the 96 printable characters of the ASCII Character Table that are present on a standard Qwerty Keyboard. Four pairs of symbols are commonly used to bracket or group symbols, words and phrases:

 (  )     Left and right parentheses.
 [  ]     Left and right (square) brackets.
 {  }     Left and right (curly) braces.
 <  >     Left and right angle brackets, also used as less than and greater than symbols.

THE   BASH   SHELL

A command shell is a basic Operating System utility that provides a human-readable interface to Users. It is named for the allegory of a nut, which has an inner kernel containing the "live" material and an outer shell to protect the sensitive kernel. The kernel is essentially a suite of command routines for comtrolling the hardware and data storage filesystems. Application programs invoke these routines in order to control the computer without needing to know the details of its operation. The shell offers a limited suite of the same capabilities to Users. Some parts of the shell are available to all Users, others are restricted for the use of one or more privileged Users, often called administrators, superusers, or root users.

Bash is the most common command shell in Linux, and is probably the default on the machine you're using. Bash is case-sensitive, as are most Unix shells.

Files and Directories

All User data in a computer is stored in files. A file is a predefined storage space containing a sequence of bytes and assigned a name by which it is accessed. The bytes within a file can be interpreted in various ways – as text, as image data, as program code, and so forth. It is therefore necessary to know the type of a file in order correctly to interpret the data within it. The file type is usually (but not always) indicated by the filename extension – a dot or period at the end of a filename followed by a sequence of letters; e.g. .txt for a textfile, .gif for a GIF image file, .mp3 for an MP3 audio file, and so on.

Files are stored within directories (or folders in Windows) which are a special type of file that contains the names and locations of ordinary files. A subdirectory is just a directory contained within another directory. Where it is necessary to differentiate between files and directories, the directory name has a slash ( / ) appended – e.g. file.ext versus directory/ The exact location of a file is given by the filepath (or path) – the filename preceded by the name or names of the directories in which it is stored; e.g. /home/mary/Desktop/data.txt The pathname separator (or delimiter) used by Linux to separate names of files and directories is slash (or forward slash)  /  (not back-slash  \  as in MS-DOS and Windows).

Bash recognizes two types of hidden files:

  1. System files are ordinary files and directories whose name begins with a dot or period; e.g. .bashrc
  2. Backup files are ordinary files whose name ends with a tilde; e.g. file.bkp~

The Commandline Prompt

The normal state of the shell is an empty commandline. This begins with a User commandline prompt at the left screen margin followed by a cursor – a single-character block or underline denoting the position at which the User can enter text. The default prompt for ordinary Users is the dollar sign  $  (not greater than  >  as in MSDOS) usually preceeded by an identification string, typically the User login name, an 'at' symbol (@) and the hostname of the machine:

user@localhost $

The Root commandline prompt is the hash sign # again preceded by an ID string:

root@localhost #

This site uses a special convention to indicate User prompts:

  •  $>  indicates a User prompt.
  •  #>  indicates a Root prompt.

These designate the prompt provided by the system and should not be entered by the User. For example, the pwd command issued by an ordinary user is shown as:

$> pwd

and the fdisk command issued by root is shown as:

#> fdisk /dev/hda

The prompt can be changed in the ~/.bashrc file; see the Bash page.

Access Permissions

Normal users have restricted access to files and directories, but the root user has access to everything. If you are logged-in as root, the command prompt changes to hash (#). The commands listed below show the default command prompt ($) followed by the command invocation.

Commands

Every command begins with the command name optionally followed by one or more switches and parameters. Commands are terminated by a newline – that is, by hitting the ENTER key. Command switches change the functionality of the command, and in Bash consists of either a dash followed by a single letter (short form), or two dashes and a word (long form) - e.g. -a --help etc. Short form switches can often be concatenated (e.g. $> ls -l -a is the same as $> ls -la) Other parameters typically provide information needed by the command, such as which file to copy or edit.

Most commands have a "help switch" givingterse information on its use. This is often invoked using one of these switches: -? -h --help More extensive help is usually available either through the man pages or the info pages (see below). Square brackets [parameter] in command documentation indicate optional items; the command can be invoked with or without them, but behaviour is different in each case.

If command output is so long that it scrolls off the top of the screen, it can be piped through a pager - a utility (short program) that presents it one screen at a time. The vertical bar or pipe symbol (| usually located above the backslash key i.e. Shift-backslash) feeds the output of one program into another. The earliest pager on Linux was named more and its modern successor is named less e.g.

$> cat filename | less
prints filename to the screen via the pager less

Note that some commands (e.g. tar) are quite ancient, and depart from today's normal practice.

BASH   COMMANDS

•   Basic  • File  • System  • Printer  • Package  • Font  •

Following are commands found on most Linux systems that are most useful for daily tasks. Some are worth learning immediately, the rest can be noted for future use. More important than learning each is to know where to find information quickly. The best method of learning them is to use a tabbed Console program such as Konsole in KDE. The manor info page about a command can be opened in one terminal window whilst the command is invoked in another. Copy files to a temporary directory to practise on them before committing changes to valuable data.

Basic Commands
pwd  $> pwd
Print working directory. Prints the absolute path of the directory from which the command is issued.
cd  $> cd [pathname]
Change directory. Changes to the directory pathname. If no directory is specified, the command defaults to the user's home directory. Two periods ( $> cd .. ) indicate the immediate parent directory (i.e. "move up one directory"). A location beginning with a slash  /  is an absolute location and one without an initial slash is relative to the present location.
mc  $> mc
Midnight Commander is a Linux clone of the once-ubiquitous Norton Commander, and is probably the most efficient way for the average user to interact with Linux. Most of the commands listed below are available in mc as menu selections, and it has many powerful features which assist with routine file and system management, including remote access via FTP. To check whether it is installed on your system, issue mc at the command prompt. If a "command not found" error is returned, ask your system administrator to install it for you, or visit www.gnome.org/projects/mc
File Commands
Creation  $> >filename
To create a file from the commandline, enter the "greater-than" sign followed by the filename, or use the cat command.
ls  $> ls -1a
List files. Lists files in the current directory. -1 (number '1') creates a single-column listing. -a lists all files including 'hidden' files (those beginning with a period). -l (lowercase 'l') gives a long format with sizes, dates and permissions.
less  $> less filename
Page output. Displays output from a command a screen at a time so that long listings can be read in pages. Use the UP and DOWN ARROW or SPACEBAR keys to move through the output. Usually used with the pipe redirection, the vertical bar symbol ( | ) which sends output from one command to another – e.g.
  $> ls -1 | less
To get out of less use q (the 'q' key).
zless  $> zless filename
List compressed file. Displays a compressed text file using less
find  $> find . -name filespec
Find files or directories. This is a complex and powerful command. The version given above searches the current directory and all directories within it for a name given by the filespec. If wildcards are used the filespec must be in doublequotes. This command has too many options for casual use; if you are searching for a file (e.g. install.log) in a directory branch, pipe ls through grep e.g.:
  $> ls -R|grep install*
cat  $> cat filename [filename]
Catenate files. To catenate is to connect in a series of links. This command has a number of uses, the simplest being to print a file to the screen. It can also be used to join several files into a single file with   $> cat file1 file2 > outfile
To create a file named filename and enter text into it, issue   $> cat > filename and use Control-D to terminate entry and return to the command prompt.
mv  $> mv filename /directory/filename
Move or rename a file or files. Moves a file(s) from the current directory to another, and optionally renames them. Can also be used to rename files within the current directory if the destination is a different filename.
rename  $> rename oldname newname files ...
Rename files. This is not a standard Linux command, but is available on many systems. If you'd like a bash script to do the job, click here to view the script, save it as 'rename' in /usr/local/bin if you've got root permission, or in your own ~/bin directory ($md bin ), and set the permissions to 755 (chmod 755 rename ).
cp  $> cp oldname newname
Copy file. Copies a file(s) to another name or another directory.
chmod  $> chmod 777 filename
Change file mode. Changes the access permissions of files and directories. 400, 200, 100 = user read, write, execute; 40, 20, 10 = group read, write, execute; 4, 2, 1 = other read, write, execute. The -R option recurses directories.
chgrp  $> chgrp group filename
Change the group membership of a file(s).
groups  $> groups
Print the groups of which the user is a member.
newgrp  $> newgrp groupname
Change the user's current group ID.
mkisofs  $> mkisofs filename pathname
Make an ISO filesystem. A premastering program for creating an ISO image for a CDROM.
System Information Commands
id  $> id
Print basic information about the user. Prints User ID (uid), Group ID (gid), and the groups of which the user is a member.
su  $> su
Set user. Allows a user to swich identity to another user.
help  $> help [command]
Print help information. Without command a list of built-in commands is printed. For help on a command not in the list, issue the command with --help following it, or use the info command.
man  $> man [command]
Print a manual page. This is the central repository of information about the Linux system. Terse, often unhelpful, full of unexplained abbreviations, the man pages are nevertheless a very useful tool.
info  $> info [command]
Print information about a command. A friendlier version of "man", which defaults to providing man pages where nothing else is available.
history  $> history
Print commandline history. Commands issued at the command prompt are stored in a history list which can be printed to the display using this command. The UP ARROW and DOWN ARROW keys move backwards and forwards through the history list, and are a convenient way or reissuing previous commands.
$> history | tail will print the last ten commands.
xset  $> xset [-OPTIONS]
List or modify user display settings. The -q switch lists the current settings.
logname  $> logname
Print the users login name.
whoami  $> whoami
Prints the user name associated with the current effective user id.
groups  $> groups
Prints the names of the primary and any supplementary groups for each given USERNAME, or the current process if no names are given.
users  $> users
Prints on a single line a blank-separated list of user names of users currently logged in to the current host.
who  $> who
Prints information about users who are currently logged on.
date  $> date
Prints current time and date.
uname  $> uname -a
Prints information about the machine and operating system it is run on. The -a option prints all options.
hostname  $> hostname [HOSTNAME]
Prints or sets the hostname.
yes  $> yes TEXTSTRING
Prints the commandline arguments until stopped. Use Ctl-C to stop printing. Useful for certain tests.
echo  $> echo [OPTION] [STRING] ...
Print strings. Most often used on the commandline to print the environment variables, e.g. $echo $PATH
printf  $> printf [FORMAT] [ARGUMENT] ...
Prints a formatted string. Similar to the C language printf() command.
factor  $> factor [ARGUMENT]
Prints prime factors of a number. With no argument reads from STDIN.
seq  $> seq [OPTIONS] ][FIRST] [STEP]] LAST
Prints numbers from FIRST to LAST at intervals of STEP.
set  $> set
Prints or sets environment variables.
Storage Devices
df  $> df
Disk free. Prints the amount of free space on all mounted drives.
du  $> du
Disk usage. Prints the amount of storage used by the current directories and all directories within it, with totals. Useful for determining the amount of disk space occupied by various directories.
File and Directory Permissions

Each file and directory in Linux has an owner and a group, with access permissions assigned individually. Three access types are defined – read, write and execute – identified by the letters r, w and x. The meaning of these is self-evident for files; for directories, read and execute permissions are usually assigned identically.

  • Read permission only – the directory cannot be entered, but filenames within it can be listed without any other information.
  • Write permission only – the directory cannot be entered, but files can be added to or deleted from it.
  • Execute permission only – the directory can be entered, but filenames cannot be listed.
These permissions can be assigned or changed in various ways. Although single-letter abbreviations can be used to refer to them, the octal numbers used by the filesystem are easier to remember once familiarity is gained.
 
Permission Special Owner Group Other
Read - 400 40 4
Write - 200 20 2
Execute - 100 10 1
SUID 4000 - - -
SGID 2000 - - -
Sticky bit 1000 - - -

 

To assign multiple permissions, these numbers are summed – for example, all permissions for the owner, read and write for the group, and read-only for others results in a permission number of 764.

There are other numbers that can be assigned, but are not used as often. One of these is the so-called 'sticky bit', used nowadays only on directories. If the sticky bit is set on a directory, files inside the directory may be renamed or removed only by the owner of the file, the owner of the directory, or the superuser (even if the modes of the directory would otherwise allow such an operation). On some systems, any user who can write to a file can also delete it. This feature was added to keep an ordinary user from deleting another's files. The sticky bit is set by prepending a one to the permissions number – e.g. $chmod 1777 dirname

The SGID bit on a directory controls the way that groups are assigned for files created in the directory. If the SGID bit is set, files created in the directory have the same group as the directory if the process creating the file also is in that group. Otherwise, if the SGID bit is not set, or if the process is not in the same group, files created inside the directory have the same group as the user's effective group ID (usually the primary group ID).

Here are some basic rules about file permissions:

  • When a new file is created, it belongs to the user creating it.
  • When a file is appended with >>file the owner doesn't change because no new file is created.
  • When a file is renamed, the ownership doesn't change unless it is moved to another filesystem, when the moved file will belong to the user executing the move, since the file must be copied and the original deleted.
  • When a file is copied, the copy belongs to the user making the copy.

The umask (user file-creation mode mask) is a four-digit octal number used to determine the file permission for newly created files. Every process has its own umask, inherited from its parent process. The umask specifies the permissions you do not want given by default to newly created files and directories. umask works by doing a bitwise AND with the bitwise complement of the umask. Bits that are set in the umask correspond to permissions that are not automatically assigned to newly created files. By default, most UNIX versions specify an octal mode of 666 (any user can read or write the file) when new files are created. Likewise, new programs are created with a mode of 777 (any user can read, write, or execute the program). Normally, the umask is set in the .login, .cshrc, or .profile files, or in the system /etc/profile file. A recent trend among computing centers has been to set up new accounts with a umask of 077, so a user's files will, by default, be unreadable by anyone else on the system unless the user makes a conscious choice to make them readable.

chmod  $> chmod 777 filename
Change file or directory mode. Changes the access permissions of files or directories. 400, 200, 100 = user read, write, execute; 40, 20, 10 = group read, write, execute; 4, 2, 1 = other read, write, execute. The -R option recurses directories.
chown  $> chown owner file
Change the owner of files or directories. Can simultaneously change the group ownership if used with a colon between the owner name and group name, i.e. $chown owner:group file
chgrp  $> chgrp group filename
Change the group ownership of files or directories. An alternative to using chown
groups  $> groups
Print the groups of which the user is a member to the screen. The user's default group is printed first.
umask  $> umask
Print the user's umask to the screen. If followed by an octal number, umask will be changed to that value, and the permissions of any file created by the user will be set to the binary complement of the value of umask. The default is usually 022 (file permissions 755).
Printer Control Commands
Linux has many powerful commands for managing printers. Most are designed for use in a networking environment, but an understanding of the basics can be of considerable assistance to workstation users. All of the commands listed below have several options which should be investigated prior to use.
Queue status  $> lpq
Query the status of the printer queue, listing all current jobs.
Start daemon  $> lpd
Stop the print daemon. The print daemon is normally started during system initialization, but there are times when it needs to be stopped and started manually.
Clear queue  $> lprm
Remove the User's current job from the print queue.
Print control  $> lpc
A general-purpose tool for managing all aspects of printing.
Package Management Commands

The most popular way of distributing applications for Linux is in RedHat Package Manager format, or RPM's. The $rpm command can install, upgrade and remove applications using the RPM files. There are many other options and capabilities – see 'info rpm'.

Install  $> rpm -ivh PACKAGENAME.rpm
Basic command to install (-i) a package in verbose (-v) mode with a line of hashes (-h) printed to indicate progress.
Uninstall  $> rpm -e PACKAGENAME.rpm
Basic command to uninstall (-e) a package.
Upgrade  $> rpm -Uvh PACKAGENAME.rpm
Upgrade (-U) a package – i.e. upgrade if installed, or install if not present.
Freshen  $> rpm -Fvh PACKAGENAME.rpm
Freshen (-F) a package – i.e. upgrade it only if already installed.
Freshen all  $> rpm -Fvha PACKAGENAME.rpm
Freshen (-F) all (-a) packages – i.e. upgrade them only if already installed.
Query  $> rpm -q FILENAME
Query (-q) whether a package is installed – e.g. rpm -q mc
List files  $> rpm -ql FILENAME
Lists (-l) all files belonging to a package.
List docn  $> rpm -qd FILENAME
Lists all documaentation (-d) files belonging to a package.
List configs  $> rpm -qc FILENAME
Lists all configuration (-c) files belonging to a package.
List deps  $> rpm -qpR PACKAGENAME.rpm
Queries (-q) a package (-p) for required (-R) packages – i.e. dependencies.
Query RPM  $> rpm -qpi PACKAGENAME.rpm
Queries (-q) a package (-p) for information (-i) about it.
Query RPM  $> rpm -qpia PACKAGENAME.rpm > rpminfo.txt
Queries (-q) all (-a) packages (-p) for information (-i) about them and saves the result in a textfile.
Font & Colour Commands

The standard directory for fonts in XWindows is /usr/X11R6/lib/X11/fonts/ in this are several subdirectories, each with a selection of fonts in a particular class. Linux uses a 14-part identifier for fonts to specify all characteristics in a common format. The xselfont command allows this to be specified from a series of drop-down menus in a GUI interface, with a display of all characters in the selected family.

xlsfonts  $> xlsfonts
List the currently registered fonts. The best way to list all available fonts and optionally get information about them.
xfontsel  $> xfontsel
Select fonts. The best way to select a font from those available. Opens a GUI window showing the 14-part font specification with drop-down menu selections.
xfd  $> xfd -fn fontname
Display a matrix of characters in a font. The best way to examine characters in a required font.
Font path  $> xset -q
List the current font path. Outputs a list of settings, amongst which is the search path for fonts used by the console. This is not the path used in XWindows, which is generally in /usr/X11R6/lib/X11/fonts/
showrgb  $> showrgb
List defined colours and their values. Lists the file in /usr/X11R6/lib/X11/rgb.txt