Recent content

Linux shell commands

Keyboard

The linux shell command line interface is a powerful tool for performing system administration tasks. In comparison a graphical user interface (GUI) is easier to use but has limitations: (i) confined to perform specific tasks, (ii) required to navigate through menus and (iii) not easily configurable to perform batch jobs.

Some of the advantages in using the command line interface are:

  • It is often faster to type a command on the keyboard than having to navigate menus in a GUI
  • The command line interface usually requires less resources than a GUI
  • Commands can be used in scripting to produce highly customisable and powerful tools to perform specific tasks

Many books and online resources are available on shell commands. As a starting point a self-contained manual page is available at the console by using the man command:

manname_of_command

For example the following command will provide details about the du command

$ man du

DU(1)                            User Commands                           DU(1)

NAME

       du - estimate file space usage

SYNOPSIS

       du [OPTION]... [FILE]...

       du [OPTION]... --files0-from=F

DESCRIPTION

       Summarize disk usage of each FILE, recursively for directories.

       Mandatory  arguments  to  long  options are mandatory for short options

       too.

       -a, --all

              write counts for all files, not just directories

       --apparent-size

              print apparent sizes,  rather  than  disk  usage;  although  the

              apparent  size is usually smaller, it may be larger due to holes

              in (`sparse') files, internal  fragmentation,  indirect  blocks,

              and the like

       -B, --block-size=SIZE

              use SIZE-byte blocks

etc...

 

Command Line Reference

A summary of commonly used (bash shell) commands is tabulated below. Specific examples are given in the sections that follow.

Basic Commands (Navigation and Disk Space)
cdChange directory
cpCopy files or directories
dfReport file system disk space usage
duEstimate the amount of disk space used by file(s)/directories
lsList directory contents
pwdDisplay the name of the current directory
rmDelete files or directories
Files and Permissions
catConcatenate files (print contents to standard output)
chmodSet file permissions
chownSet file ownership and group
diffCompare the contents of two files and report the difference
fileDetermine the file type
headDisplay the first part of a file
lessView a file (with backward screen movement)
moreView a file (a screen at a time)
sortSort lines in a text file
statDisplay file details and attributes
tailDisplay the last part of a file
Searching & String Manipulation
awkPattern scanning and processing
findSearch for files in a directory structure
grepSearch for patterns in a file
sedStream editor for performing text transformations
locateFind files by name
System Administration & Diagnostics
dmesgPrint the contents of the kernel ring buffer (useful for troubleshooting hardware issues)
fdiskDisk partition table tool
fingerDisplay user information
lsofList open files
lspciList PCI devices
psReporting tool of current processes
killSend a signal to a running process (a terminate signal by default)
shutdownShutdown the system
topDisplay linux tasks
unamePrint system information (e.g. hostname, kernel version)
mountMount a filesystem
wDisplay currently logged in users
Archiving & Backups
rsyncFile copy & synchronisation tool. Often used for backing up files to remote server
tarArchiving utility
Networking & Remote Access
hostnameDisplay the system hostname
ifconfigConfigure a network interface
nslookupQuery a host
pingTest the connectivity to a host
sshSecure shell access - Remote login program

 

Examples

Basic Commands - Directories & Files

lsList the contents of the current directory
ls -latList of the contents of the current directory. Include hidden files, long listing format and sort by modification time
ls -RList the contents of the current directory. Include all subdirectories in the long listing format
pwdDisplay the name of the current directory
cd ..Move up one directory level (from the current working directory)
cd /home/joe_blogsChange the current working directory to /home/joe_blogs
cp imagetest.jpg imagetest2.jpgCopy the file imagetest.jpg to imagetest2.jpg
cp -rp directory1 directory2Copy the directory1 (and all contents within) to directory2, preserving file permissions
mv movie1.iso movie2.isoRename the file movie1.iso to movie2.iso
rm module.hDelete the file module.h
rm -r sqlite3Delete the directory sqlite3. The recurse option (-r) will delete the directory and all files contained within
mkdir ImagesCreate a directory called Images (in the current working directory)
rmdir fontconfigRemove the directory fontconfig. This command will only work if the directory is empty

Basic Commands - Disk Space Monitoring

dfShow free space on all mounted file systems
df -hShow free space on all mounted file systems in human readable format (e.g. MB, GB, ...)
df -h /homeShow the amount of free space on the file system /home in human readable format
duReport the disk usage of all files in the current directory (recurse into sub directories) in kB
du -shReport the total disk usage of all files in the current directory (recurse into sub directories) in kB
du * | sort -nr | head -10Create a report of disk usage of all files in the current directory. Show the top 10 files (sorted by file size)

Files & Permissions

cat graphics.hPrint the contents of the file graphics.h to the screen
more /etc/profileDisplay the contents of the file /etc/profile one screen full at a time
less textfile.datDisplay the contents of the file /etc/profile. Similar to more with the added feature that backward movement is allowed
head license.datDisplay the first part of the file license.dat
tail /etc/passwdDisplay the last part of the file /etc/passwd. The default is to display the last 10 lines if no options are given
tail -f /var/log/messagesDisplay the last part of the file /var/log/messages with the follow option. The output will be updated as data is appended to the file
chmod g+rw archive.md5Set the group permission of the file archive.md5 to read and write
chmod 644 cerfiticate.pdfSet the group permission of the file archive.md5 to read and write
chown -R john backupsSet the ownership of the directory backups to john. The recursive option (-R) has been selected to operate on all files and sub-directories inside the directory called backups
file patch.pyReport the file type (for the file patch.py). Some possible results include (i) ASCII text files, (ii) binaries and (iii) script executables
stat grid.bmpDisplay the status of a file, i.e. whether it is a file or directory, permissions, modification time etc ...
sort -nr filenameSort the contents of the filename using a numerical sort in reverse order
sort -k2 filenameSort the contents of the filename by the 2nd field (the default field delimeter is a space)
diff file1 file2Report the differences between file1 and file2. Lines from file1 (not in file2) are displayed with < (at the beginning of each line). Lines in file2 (not in file1) are displayed with >
diff -y file1 file2Report the differences between file1 and file2. Display the output in 2 columns side by side

Searching - Files

find . -type f -name '*.pdf'Search for files ending in .pdf in the current directory (and recurse into sub-directories)
find ~ -type f -name '*.doc' | wc -lCount the number of files ending in .doc in the home directory (~). Note how the output of the find command is piped into the wc command
find /var/log -type f -mtime +365Search for files in /var/log that were modified over a year ago
locate *.jpgFiles all files ending in jpg (*.jpg) on the system. locate relies on a system database (updatedb) to be update daily by cron.

Searching - Text file and string manipulation

grep "joe" filename.txtSearch for the string "joe" in the file filename.txt
grep -A 3 fred /etc/passwdSearch for "fred" in the file /etc/passwd. If there is a match also display the next 3 lines
grep -i error report.logSearch for the string "error" in the file report.log. The -i option indicates that the match is case-insensitive, e.g. ERROR will be reported as a match
grep -v "apples" list.datDisplay lines in the file list.dat which don't match the pattern "apples". The -v option inverts the match
grep -v '^$' file.datDisplay the contents of the file file.dat with the exception of blank lines. The special characters ^ and $ refer to the beginning and the end of a line respectively
awk '{print $1}' file.datPrint the 1st column of the contents of the file file.dat
ls -l | awk '{print $NF}'Print the last field on the output of the command ls -l
awk -F":" '{print $3}' /etc/passwdPrint a list of all the user IDs on the current system, i.e. for each line in /etc/passwd print out the 3rd field. The field delimeter is the colon
sed 's/John/Bill/g' address.datChange all instances of the string "John" to "Bill" in the file address.dat. The command option "s" denotes substitution and the "g" denotes global replacement, i.e. make changes to the whole file
sed '/^$/d' x.datRemove all blank lines using the file x.dat as input data. ^ and $ are special characters denoting the beginning and end of a line respectively

Archiving & Backups

tar -cvf bin.tar binCreate the tar archive file bin.tar of all files in the bin directory: Options: -c = create, -v = verbose output and -f specifies the tar file
tar -tf bin.tarList the contents of the tar file bin.tar. Options: -t = list the contents, -f specifies the filename
tar -xvf bin.tarExtract the contents of bin.tar into to the current directory. Options: -x = extract, -v = verbose output and -f specifies the tar file
rsync -av /directory /dest/pathCopy files from /directory to /dest/path (archive mode and verbose output)
rsync -avx /var /some/directoryCopy files from /var to /some/directory (archive mode, verbose output and don't cross file system boundaries)
rsync -av --delete /home/joe user@host:/backupCopy files using ssh from /home/joe (archive mode & verbose output) to the directory /backup on the remote server with hostname host. Use user to authenticate and delete files at the destination that don't exist on the source machine (i.e. /home/joe)

System Administration & Diagnostics

topDisplay linux tasks
ps -aefDisplay all running processes in a full format listing
uptimeReport how long the system has been up and running (in days)
uname -aPrint system information such as hostname, kernel version, platform and processor type
dmesgPrint the kernel ring buffer. Useful for diagnosing hardware problems
cat /etc/issueReport the operating system
passwdChange the user password
id Print the user ID of the current user
id userPrint the user (and group) ID of user
lsofList all open files
lsof /dataList all open files in the filesystem /data
lsof -p 12345List all open files 
lsof -u user123List all files that are currently open by the user user123
kill 12345Send the terminal signal to process with ID 12345. This will attempt to kill the process (with signal id 15)
kill -9 12345Send the kill signal to the process with ID 12345. This is more aggressive than the previous example
exitexit the current shell
shutdown -r nowReboot the system immediately
finger usernameDisplay information about the user username
suSwitch user (become super user)
su usernameSwitch to user username in the current login session
su - usernameSwitch to user username in the current login session. Setup the user environment as if the user username logged in directly
sudo commandExecute the command as another user. In this case there is no argument provided for the username (i.e. - username). The command will be executed as the root user
mount /homemount the filesystem labelled /home (in /etc/fstab)
mount -t iso9660 /dev/sr0 /mnt/cdmount a CD (with device name /dev/sr0) to the mount point /mnt/cd
wShow a list of users currently logged into the system

Networking & Remote Access

hostnameDisplay the hostname (of the current session)
ifconfig -aDisplay details of all network interfaces (even if they are down)
ifconfig eth1 192.168.2.1Assign 192.168.2.1 as the IP address for the network interface eth0
ifconfig eth0 upEnable the network interface eth0
nslookup www.example.comQuery the name server www.example.com
nslookup 192.168.2.10Query the server with IP address 192.168.2.10
ping 74.125.237.50ping the machine with IP address 74.125.237.50
ping domainname.comping the mahine with DNS name domainname.com
ssh -l joe machinenameConnect using a secure shell login program to the host called machinename as the user joe
ssh -X -i key2 fred@machineConnect using a secure shell login program to the host called machine with X-forwarding enabled as the user fred and using the private key key2

References and Related links

A basic linux command guidehttp://www.my-guides.net/en/content/view/29/26/
A more comprehensive guidehttp://www.pixelbeat.org/cmdline.html
Unix (Linux) tutorial for beginnershttp://www.ee.surrey.ac.uk/Teaching/Unix/

Further Reading

  • Linux Command Line and Shell Scripting Bible (Richard Blum)
  • Learning the bash Shell (Cameron Newman)
  • Unix and Linux System Administration Handbook (Evi Nemeth, Garth Snyder, Trent R. Hein and Ben Whaley)