You are on page 1of 33

Linux Command Line: APT packages

tool (Debian, Ubuntu


and alike)

Command

Description

# apt-cache search [package]

returns list of packages which corresponds string


"searched-packages" [man]

# apt-cdrom install [package]

install / upgrade a deb package from cdrom


[man]

# apt-get install [package]

install / upgrade a deb package

# apt-get update

update the package list

# apt-get upgrade

upgrade all of the installed packages

# apt-get remove [package]

remove a deb package from system

# apt-get check

verify correct resolution of dependencies

# apt-get clean

clean up cache from packages downloaded


[man]

Linux Command Line: Archives

[man]

[man]
[man]
[man]
[man]

and compressed files

Command
Description
# bunzip2 file1.bz2

decompress a file called 'file1.bz2'

[man]

# bzip2 file1

compress a file called 'file1'

# gunzip file1.gz

decompress a file called 'file1.gz'

# gzip file1

compress a file called 'file1'

# gzip -9 file1

compress with maximum compression

# rar a file1.rar test_file

create an archive rar called 'file1.rar'

# rar a file1.rar file1 file2 dir1

compress 'file1', 'file2' and 'dir1'


simultaneously [man]

# rar x file1.rar

decompress rar archive

# tar -cvf archive.tar file1

create a uncompressed tarball

# tar -cvf archive.tar file1 file2 dir1

create an archive containing 'file1', 'file2' and


'dir1' [man]

# tar -tf archive.tar

show contents of an archive

# tar -xvf archive.tar

extract a tarball

# tar -xvf archive.tar -C /tmp

extract a tarball into / tmp

# tar -cvfj archive.tar.bz2 dir1

create a tarball compressed into bzip2

# tar -xvfj archive.tar.bz2

decompress a compressed tar archive in bzip2


[man]

# tar -cvfz archive.tar.gz dir1

create a tarball compressed into gzip

# tar -xvfz archive.tar.gz

decompress a compressed tar archive in gzip

[man]
[man]

[man]
[man]
[man]

[man]
[man]

[man]

[man]
[man]
[man]

[man]

[man]
# unrar x file1.rar

decompress rar archive

[man]

# unzip file1.zip

decompress a zip archive

# zip file1.zip file1

create an archive compressed in zip

# zip -r file1.zip file1 file2 dir1

compress in zip several files and directories


simultaneously [man]

[man]
[man]

Linux Command Line: Backup


Command

Description

# find /var/log -name '*.log' | tar cv --filesfrom=- | bzip2 > log.tar.bz2

find all files with '.log' extention and make an


bzip archive [man]

# find /home/user1 -name '*.txt' | xargs cp


-av --target-directory=/home/backup/
--parents

find and copy all files with '.txt' extention from a


directory to another [man]

# dd bs=1M if=/dev/hda | gzip | ssh


user@ip_addr 'dd of=hda.gz'

make a backup of a local hard disk on remote


host via ssh [man]

# dd if=/dev/sda of=/tmp/file1

backup content of the harddrive to a file

# dd if=/dev/hda of=/dev/fd0 bs=512


count=1

make a copy of MBR (Master Boot Record) to


floppy [man]

# dd if=/dev/fd0 of=/dev/hda bs=512


count=1

restore MBR from backup copy saved to floppy


[man]

# dump -0aj -f /tmp/home0.bak /home

make a full backup of directory '/home'

# dump -1aj -f /tmp/home0.bak /home

make a incremental backup of directory '/home'


[man]

# restore -if /tmp/home0.bak

restoring a backup interactively

# rsync -rogpav --delete /home /tmp

synchronization between directories

# rsync -rogpav -e ssh --delete /home


ip_address:/tmp

rsync via SSH tunnel

# rsync -az -e ssh --delete


ip_addr:/home/public /home/local

synchronize a local directory with a remote


directory via ssh and compression [man]

# rsync -az -e ssh --delete /home/local


ip_addr:/home/public

synchronize a remote directory with a local


directory via ssh and compression [man]

# tar -Puf backup.tar /home/user

make a incremental backup of directory


'/home/user' [man]

[man]

[man]

[man]
[man]

[man]

# ( cd /tmp/local/ && tar c . ) | ssh -C


copy content of a directory on remote directory
user@ip_addr 'cd /home/share/ && tar x -p' via ssh [man]
# ( tar c /home ) | ssh -C user@ip_addr
'cd /home/backup-home && tar x -p'

copy a local directory on remote directory via


ssh [man]

# tar cf - . | (cd /tmp/backup ; tar xf - )

local copy preserving permits and links from a


directory to another [man]

Linux Command Line: CDROM

Command

Description

# cd-paranoia -B

rip audio tracks from a CD to wav files

# cd-paranoia --

rip first three audio tracks from a CD to wav files


[man]

# cdrecord -v gracetime=2 dev=/dev/cdrom clean a rewritable cdrom


-eject blank=fast -force

[man]

[man]

# cdrecord -v dev=/dev/cdrom cd.iso

burn an ISO image

# gzip -dc cd_iso.gz | cdrecord


dev=/dev/cdrom -

burn a compressed ISO image

# cdrecord --scanbus

scan bus to identify the channel scsi

# dd if=/dev/hdc | md5sum

perform an md5sum on a device, like a CD


[man]

# mkisofs /dev/cdrom > cd.iso

create an iso image of cdrom on disk

# mkisofs /dev/cdrom | gzip > cd_iso.gz

create a compressed iso image of cdrom on disk


[man]

# mkisofs -J -allow-leading-dots -R -V

create an iso image of a directory

# mount -o loop cd.iso /mnt/iso

mount an ISO image

Linux Command Line: Character set

[man]
[man]
[man]

[man]

[man]

[man]

and Format file

conversion
Command

Description

# dos2unix filedos.txt fileunix.txt

convert a text file format from MSDOS to UNIX


[man]

# recode ..HTML < page.txt > page.html

convert a text file to html

# recode -l | more

show all available formats conversion

# unix2dos fileunix.txt filedos.txt

convert a text file format from UNIX to MSDOS

[man]
[man]

Linux Command Line: DEB

packages (Debian, Ubuntu and


like)

Command

Description

# dpkg -i [package.deb]

install / upgrade a deb package

# dpkg -r [package]

remove a deb package from the system

# dpkg -l

show all deb packages installed on the system


[man]

# dpkg -l | grep httpd

show all deb packages with the name "httpd"


[man]

# dpkg -s [package]

obtain information on a specific package installed


on system [man]

# dpkg -L [package]

show list of files provided by a package installed


on system [man]

# dpkg --contents [package.deb]

show list of files provided by a package not yet


installed [man]

# dpkg -S /bin/ping

verify which package belongs to a given file


[man]

Linux Command Line: Disk

[man]
[man]

Space

Command

Description

# df -h

show list of partitions mounted

[man]

# dpkg-query -W -f='${Installed-Size;10}t$ show the used space by installed deb packages,


{Package}n' | sort -k1,1n
sorting by size (debian, ubuntu and alike)
[man]
# du -sh dir1

estimate space used by directory 'dir1'

[man]

# du -sk * | sort -rn

show size of the files and directories sorted by


size [man]

# ls -lSr |more

show size of the files and directories ordered by


size [man]

# rpm -q -a --qf '%10{SIZE}t%{NAME}n' | show space used by rpm packages installed


sort -k1,1n
sorted by size (fedora, redhat and like) [man]

Linux Command Line: File

search

Command

Description

# find / -name file1

search file and directory into root filesystem


from '/' [man]

# find / -user user1

search files and directories belonging to 'user1'


[man]

# find /home/user1 -name \*.bin

search files with '. bin' extension within directory


'/ home/user1' [man]

# find /usr/bin -type f -atime +100

search binary files are not used in the last 100


days [man]

# find /usr/bin -type f -mtime -10

search files created or changed within 10 days


[man]

# find / -name *.rpm -exec chmod 755


'{}' \;

search files with '.rpm' extension and modify


permits [man]

# find / -xdev -name \*.rpm

search files with '.rpm' extension ignoring


removable partitions as cdrom, pen-drive, etc.
[man]

# locate \*.ps

find files with the '.ps' extension - first run


'updatedb' command [man]

# whereis halt

show location of a binary file, source or man


[man]

# which halt

show full path to a binary / executable

Linux Command Line: Files

[man]

and Directory

Command

Description

# cd /home

enter to directory '/ home'

# cd ..

go back one level

# cd ../..

go back two levels

# cd

go to home directory

[man]

# cd ~user1

go to home directory

[man]

# cd -

go to previous directory

# cp file1 file2

copying a file

# cp dir/* .

copy all files of a directory within the current


work directory [man]

# cp -a /tmp/dir1 .

copy a directory within the current work


directory [man]

# cp -a dir1 dir2

copy a directory

# cp file file1

outputs the mime type of the file as text

# iconv -l

lists known encodings

[man]

[man]
[man]

[man]

[man]

[man]

[man]

[man]

# iconv -f fromEncoding -t toEncoding


inputFile > outputFile

converting the coding of characters from one


format to another [man]

# find . -maxdepth 1 -name *.jpg -print


-exec convert

batch resize files in the current directory and


send them to a thumbnails directory (requires
convert from Imagemagick) [man]

# ln -s file1 lnk1

create a symbolic link to file or directory

# ln file1 lnk1

create a physical link to file or directory

# ls

view files of directory

[man]

# ls -F

view files of directory

[man]

# ls -l

show details of files and directory

# ls -a

show hidden files

# ls *[0-9]*

show files and directory containing numbers


[man]

# lstree

show files and directories in a tree starting from


root(2) [man]

# mkdir dir1

create a directory called 'dir1'

# mkdir dir1 dir2

create two directories simultaneously

# mkdir -p /tmp/dir1/dir2

create a directory tree

# mv dir1 new_dir

rename / move a file or directory

# pwd

show the path of work directory

# rm -f file1

delete file called 'file1'

# rm -rf dir1

remove a directory called 'dir1' and contents


recursively [man]

# rm -rf dir1 dir2

remove two directories and their contents


recursively [man]

# rmdir dir1

delete directory called 'dir1'

# touch -t 0712250000 file1

modify timestamp of a file or directory (YYMMDDhhmm) [man]

# tree

show files and directories in a tree starting from


root(1) [man]

[man]
[man]

[man]

[man]

[man]
[man]

[man]
[man]
[man]

[man]

[man]

Linux Command Line: Filesystem Analysis


Command

Description

# badblocks -v /dev/hda1

check bad blocks on disk hda1

# dosfsck /dev/hda1

repair / check integrity of dos filesystems on disk


hda1 [man]

# e2fsck /dev/hda1

repair / check integrity of ext2 filesystem on disk


hda1 [man]

# e2fsck -j /dev/hda1

repair / check integrity of ext3 filesystem on disk


hda1 [man]

# fsck /dev/hda1

repair / check integrity of linux filesystem on


disk hda1 [man]

# fsck.ext2 /dev/hda1

repair / check integrity of ext2 filesystem on disk


hda1 [man]

# fsck.ext3 /dev/hda1

repair / check integrity of ext3 filesystem on disk


hda1 [man]

# fsck.vfat /dev/hda1

repair / check integrity of fat filesystem on disk


hda1 [man]

# fsck.msdos /dev/hda1

repair / check integrity of dos filesystem on disk


hda1 [man]

Linux Command Line: Filesystem

SWAP

Command

Description

# mkswap /dev/hda3

create a swap filesystem

# swapon /dev/hda3

activating a new swap partition

# swapon /dev/hda2 /dev/hdb3

activate two swap partitions

Linux Command Line: Format

[man]

[man]
[man]

[man]

a Filesystem

Command

Description

# fdformat -n /dev/fd0

format a floppy disk

# mke2fs /dev/hda1

create a filesystem type linux ext2 on hda1


partition [man]

# mke2fs -j /dev/hda1

create a filesystem type linux ext3 (journal) on


hda1 partition [man]

# mkfs /dev/hda1

create a filesystem type linux on hda1 partition


[man]

# mkfs -t vfat 32 -F /dev/hda1

create a FAT32 filesystem

# mkswap /dev/hda3

create a swap filesystem

Linux Command Line: IPTABLES

[man]

[man]
[man]

(firewall)

Command

Description

# iptables -t filter -L

show all chains of filtering table

# iptables -t nat -L

show all chains of nat table

# iptables -t filter -F

clear all rules from filtering table

# iptables -t nat -F

clear all rules from table nat

# iptables -t filter -X

delete any chains created by user

# iptables -t filter -A INPUT -p tcp --dport


telnet -j ACCEPT

allow telnet connections to input

# iptables -t filter -A OUTPUT -p tcp --dport


http -j DROP

block HTTP connections to output

# iptables -t filter -A FORWARD -p tcp


--dport pop3 -j ACCEPT

allow POP3 connections to forward chain

# iptables -t filter -A INPUT -j LOG --logprefix

Logging on input chain

[man]

[man]
[man]

[man]
[man]
[man]
[man]
[man]

[man]

# iptables -t nat -A POSTROUTING -o eth0 -j configure a PAT (Port Address Traslation) on eth0
MASQUERADE
masking outbound packets [man]
# iptables -t nat -A PREROUTING -d
192.168.0.1 -p tcp -m tcp --dport 22 -j
DNAT --to-destination 10.0.0.2:22

redirect packets addressed to a host to another


host [man]

Linux Command Line: Microsoft

Windows networks
(samba)

Command

Description

# mount -t smbfs -o
username=user,password=pass
//WinClient/share /mnt/share

mount a windows network share

# nbtscan ip_addr

netbios name resolution

[man]

# nmblookup -A ip_addr

netbios name resolution

[man]

# smbclient -L ip_addr/hostname

show remote shares of a windows host

# smbget -Rr smb://ip_addr/share

like wget can download files from a host


windows via smb [man]

[man]

[man]

Linux Command Line: Monitoring

and debugging

Command

Description

# free -m

displays status of RAM in megabytes

# kill -9 process_id

force closure of the process and finish it

# kill -1 process_id

force a process to reload configuration

# last reboot

show history reboot

# lsmod

display kernel loaded

# lsof -p process_id

display a list of files opened by processes


[man]

# lsof /home/user1

displays a list of open files in a given path


system [man]

# ps -eafw

displays linux tasks

# ps -e -o pid,args --forest

displays linux tasks in a hierarchical mode


[man]

# pstree

Shows a tree system processes

# smartctl -A /dev/hda

monitoring reliability of a hard-disk through


SMART [man]

# smartctl -i /dev/hda

check if SMART is active on a hard-disk

# strace -c ls >/dev/null

display system calls made and received by a


process [man]

# strace -f -e open ls >/dev/null

display library calls

# tail /var/log/dmesg

show events inherent to the process of booting


kernel [man]

# tail /var/log/messages

show system events

# top

display linux tasks using most cpu

# watch -n1 'cat /proc/interrupts'

display interrupts in real-time

Linux Command Line: Mounting

[man]
[man]
[man]

[man]
[man]

[man]

[man]

[man]

[man]

[man]
[man]

[man]

a Filesystem

Command

Description

# fuser -km /mnt/hda2

force umount when the device is busy

# mount /dev/hda2 /mnt/hda2

mount disk called hda2 - verify existence of the


directory '/ mnt/hda2' [man]

# mount /dev/fd0 /mnt/floppy

mount a floppy disk

# mount /dev/cdrom /mnt/cdrom

mount a cdrom / dvdrom

# mount /dev/hdc /mnt/cdrecorder

mount a cdrw / dvdrom

[man]

# mount /dev/hdb /mnt/cdrecorder

mount a cdrw / dvdrom

[man]

# mount -o loop file.iso /mnt/cdrom

mount a file or iso image

# mount -t vfat /dev/hda5 /mnt/hda5

mount a Windows FAT32 file system

[man]

[man]
[man]

[man]
[man]

# mount /dev/sda1 /mnt/usbdisk

mount a usb pen-drive or flash-drive

# mount -t smbfs -o
username=user,password=pass
//WinClient/share /mnt/share

mount a windows network share

# umount /dev/hda2

unmount disk called hda2 - exit from mount


point '/ mnt/hda2' first [man]

# umount -n /mnt/hda2

run umount without writing the file /etc/mtab useful when the file is read-only or the hard disk
is full [man]

Linux Command Line: Networking

Command

[man]

[man]

(LAN / WiFi)

Description
# dhclient eth0

active interface 'eth0' in dhcp mode

[man]

# ethtool eth0

show network statistics of eth0

# host www.example.com

lookup hostname to resolve name to ip


address and viceversa [man]

# hostname

show hostname of system

# ifconfig eth0

show configuration of an ethernet network


card [man]

# ifconfig eth0 192.168.1.1 netmask


255.255.255.0

configure IP Address

# ifconfig eth0 promisc

configure 'eth0' in promiscuous mode to gather


packets (sniffing) [man]

# ifdown eth0

disable an interface 'eth0'

# ifup eth0

activate an interface 'eth0'

# ip link show

show link status of all network interfaces


[man]

# iwconfig eth1

show wireless networks

# iwlist scan

wifi scanning to display the wireless


connections available [man]

# mii-tool eth0

show link status of 'eth0'

# netstat -tup

S[how all active network connections and their


PID [man]

# netstat -tupl

show all network services listening on the


system and their PID [man]

# netstat -rn

show routing table alike "route -n"

# nslookup www.example.com

lookup hostname to resolve name to ip


address and viceversa [man]

# route -n

show routing table

# route add -net 0/0 gw IP_Gateway

configure default gateway

# route add -net 192.168.0.0 netmask


255.255.0.0 gw 192.168.1.1

configure static route to reach network


'192.168.0.0/16' [man]

[man]

[man]

[man]

[man]
[man]

[man]

[man]

[man]

[man]
[man]

# route del 0/0 gw IP_gateway

remove static route

# echo "1" >


/proc/sys/net/ipv4/ip_forward

activate ip routing

# tcpdump tcp port 80

show all HTTP traffic

# whois www.example.com

lookup on Whois database

Linux Command Line: Other useful

[man]
[man]
[man]
[man]

commands

Command

Description

# alias hh='history'

set an alias for a command - hh = history


[man]

# apropos ...keyword

display a list of commands that pertain to


keywords of a program , useful when you know
what your program does, but you don't know the
name of the command [man]

# chsh

change shell command

# chsh --list-shells

nice command to know if you have to remote


into another box [man]

# gpg -c file1

encrypt a file with GNU Privacy Guard

[man]

# gpg file1.gpg

decrypt a file with GNU Privacy Guard

[man]

# ldd /usr/bin/ssh

show shared libraries required by ssh program


[man]

# man ping

display the on-line manual pages for example on


ping command - use '-k' option to find any
related commands [man]

# mkbootdisk --device /dev/fd0 `uname -r` create a boot floppy

[man]

[man]

# wget -r www.example.com

download an entire web site

[man]

# wget -c www.example.com/file.iso

download a file with the ability to stop the


download and resume later [man]

# echo 'wget -c www.example.com/files.iso' start a download at any given time


| at 09:00

[man]

# whatis ...keyword

displays description of what a program does


[man]

# who -a

show who is logged on, and print: time of last


system boot, dead processes, system login
processes, active processes spawned by init,
current runlevel, last system clock change
[man]

Linux Command Line: Pacman

packages tool (Arch,


Frugalware and alike)

Command

Description

# pacman -S name

Install package 'name' with dependencies

[man]
# pacman -R name

Delete package 'name' and all files of it

Linux Command Line: Permits

[man]

on Files

Command

Description

# chgrp group1 file1

change group of files

# chmod ugo+rwx directory1

set permissions reading (r), write (w) and (x)


access to users owner (u) group (g) and others
(o) [man]

# chmod go-rwx directory1

remove permits reading (r), write (w) and (x)


access to users group (g) and others (or [man]

# chmod u+s /bin/file1

set SUID bit on a binary file - the user that


running that file gets same privileges as owner
[man]

# chmod u-s /bin/file1

disable SUID bit on a binary file

# chmod g+s /home/public

set SGID bit on a directory - similar to SUID but


for directory [man]

# chmod g-s /home/public

disable SGID bit on a directory

# chmod o+t /home/public

set STIKY bit on a directory - allows files deletion


only to legitimate owners [man]

# chmod o-t /home/public

disable STIKY bit on a directory

# chown user1 file1

change owner of a file

# chown -R user1 directory1

change user owner of a directory and all the files


and directories contained inside [man]

# chown user1:group1 file1

change user and group ownership of a file


[man]

# find / -perm -u+s

view all files on the system with SUID configured


[man]

# ls -lh

show permits on files

# ls /tmp | pr -T5 -W$COLUMNS

divide terminal into 5 columns

[man]

[man]

[man]

[man]

[man]

[man]
[man]

Linux Command Line: RPM

Packages ( Fedora, Red Hat


and like)

Command

Description

# rpm -ivh [package.rpm]

install a rpm package

# rpm -ivh --nodeeps [package.rpm]

install a rpm package ignoring


dependencies requests [man]

# rpm -U [package.rpm]

upgrade a rpm package without


changing configuration files [man]

[man]

# rpm -F [package.rpm]

upgrade a rpm package only if it is


already installed [man]

# rpm -e [package]

remove a rpm package

# rpm -qa

show all rpm packages installed on the


system [man]

# rpm -qa | grep httpd

show all rpm packages with the name


"httpd" [man]

# rpm -qi [package]

obtain information on a specific


package installed [man]

# rpm -qg "System Environment/Daemons"

show rpm packages of a group


software [man]

# rpm -ql [package]

show list of files provided by a rpm


package installed [man]

# rpm -qc [package]

show list of configuration files provided


by a rpm package installed [man]

# rpm -q [package] --whatrequires

show list of dependencies required for


a rpm packet [man]

# rpm -q [package] --whatprovides

show capability provided by a rpm


package [man]

# rpm -q [package] --scripts

show scripts started during installation


/ removal [man]

# rpm -q [package] --changelog

show history of revisions of a rpm


package [man]

# rpm -qf /etc/httpd/conf/httpd.conf

verify which rpm package belongs to a


given file [man]

# rpm -qp [package.rpm] -l

show list of files provided by a rpm


package not yet installed [man]

[man]

# rpm --import /media/cdrom/RPM-GPG-KEY import public-key digital signature


[man]
# rpm --checksig [package.rpm]

verify the integrity of a rpm package


[man]

# rpm -qa gpg-pubkey

verify integrity of all rpm packages


installed [man]

# rpm -V [package]

check file size, permissions, type,


owner, group, MD5 checksum and last
modification [man]

# rpm -Va

check all rpm packages installed on


the system - use with caution [man]

# rpm -Vp [package.rpm]

verify a rpm package not yet installed


[man]

# rpm -ivh /usr/src/redhat/RPMS/`arch`/


[package.rpm]

install a package built from a rpm


source [man]

# rpm2cpio [package.rpm] | cpio --extract


--make-directories *bin*

extract executable file from a rpm


package [man]

# rpmbuild --rebuild [package.src.rpm]

build a rpm package from a rpm


source [man]

Linux Command Line: Shutdown,

Restart and Logout of a


system

Command

Description

# init 0

shutdown system(2)

# logout

leaving session

# reboot

reboot(2)

# shutdown -h now

shutdown system(1)

# shutdown -h 16:30 &

planned shutdown of the system

# shutdown -c

cancel a planned shutdown of the system


[man]

# shutdown -r now

reboot(1)

# telinit 0

shutdown system(3)

[man]

[man]

[man]
[man]

[man]
[man]

[man]

Linux Command Line: Special Attributes

on files

Command

Description

# chattr +a file1

allows write opening of a file only append


mode [man]

# chattr +c file1

allows that a file is compressed /


decompressed automatically by the kernel
[man]

# chattr +d file1

makes sure that the program ignores Dump


the files during backup [man]

# chattr +i file1

makes it an immutable file, which can not


be removed, altered, renamed or linked
[man]

# chattr +s file1

allows a file to be deleted safely

# chattr +S file1

makes sure that if a file is modified changes


are written in synchronous mode as with
sync [man]

# chattr +u file1

allows you to recover the contents of a file


even if it is canceled [man]

# lsattr

show specials attributes

Linux Command Line: System

[man]

[man]

information

Command

Description

# arch

show architecture of machine(1)

# cal 2007

show the timetable of 2007

# cat /proc/cpuinfo

show information CPU info

# cat /proc/interrupts

show interrupts

# cat /proc/meminfo

verify memory use

# cat /proc/swaps

show file(s) swap

# cat /proc/version

show version of the kernel

# cat /proc/net/dev

show network adpters and statistics

# cat /proc/mounts

show mounted file system(s)

# clock -w

save date changes on BIOS

# date

show system date

# date 041217002007.00

set date and time MonthDayhoursMinutesYear.Seconds


[man]

# dmidecode -q

show hardware system components -

[man]

[man]
[man]

[man]
[man]
[man]
[man]
[man]
[man]

[man]

[man]

(SMBIOS / DMI)

[man]

# hdparm -i /dev/hda

displays the characteristics of a hard-disk


[man]

# hdparm -tT /dev/sda

perform test reading on a hard-disk

# lspci -tv

display PCI devices

# lsusb -tv

show USB devices

# uname -m

show architecture of machine(2)

# uname -r

show used kernel version

Linux Command Line: Text

[man]

[man]
[man]
[man]

[man]

Manipulation

Command

Description

# cat example.txt | awk 'NR%2==1'

remove all even lines from example.txt


[man]

# echo a b c | awk '{print $1}'

view the first column of a line

# echo a b c | awk '{print $1,$3}'

view the first and third column of a line


[man]

# cat -n file1

number row of a file

# comm -1 file1 file2

compare contents of two files by deleting


only unique lines from 'file1' [man]

# comm -2 file1 file2

compare contents of two files by deleting


only unique lines from 'file2' [man]

# comm -3 file1 file2

compare contents of two files by deleting


only the lines that appear on both files
[man]

# diff file1 file2

find differences between two files

# grep Aug /var/log/messages

look up words "Aug" on file


'/var/log/messages' [man]

# grep ^Aug /var/log/messages

look up words that begin with "Aug" on file


'/var/log/messages' [man]

# grep [0-9] /var/log/messages

select from file '/var/log/messages' all lines


that contain numbers [man]

# grep Aug -R /var/log/*

search string "Aug" at directory '/var/log'


and below [man]

# paste file1 file2

merging contents of two files for columns


[man]

# paste -d '+' file1 file2

merging contents of two files for columns


with '+' delimiter on the center [man]

# sdiff file1 file2

find differences between two files and


merge interactively alike "diff" [man]

[man]

[man]

[man]

# sed 's/string1/string2/g' example.txt

replace "string1" with "string2" in


example.txt [man]

# sed '/^$/d' example.txt

remove all blank lines from example.txt


[man]

# sed '/ *#/d; /^$/d' example.txt

remove comments and blank lines from


example.txt [man]

# sed -e '1d' exampe.txt

eliminates the first line from file


example.txt [man]

# sed -n '/string1/p'

view only lines that contain the word


"string1" [man]

# sed -e 's/ *$//' example.txt

remove empty characters at the end of


each row [man]

# sed -e 's/string1//g' example.txt

remove only the word "string1" from text


and leave intact all [man]

# sed -n '1,5p' example.txt

print from 1th to 5th row of example.txt


[man]

# sed -n '5p;5q' example.txt

print row number 5 of example.txt

# sed -e 's/00*/0/g' example.txt

replace more zeros with a single zero


[man]

# sort file1 file2

sort contents of two files

# sort file1 file2 | uniq

sort contents of two files omitting lines


repeated [man]

# sort file1 file2 | uniq -u

sort contents of two files by viewing only


unique line [man]

# sort file1 file2 | uniq -d

sort contents of two files by viewing only


duplicate line [man]

# echo 'word' | tr '[:lower:]' '[:upper:]'

convert from lower case in upper case


[man]

[man]

[man]

Linux Command Line: Users

and Groups

Command

Description

# chage -E 2005-12-31 user1

set deadline for user password

# groupadd [group]

create a new group

# groupdel [group]

delete a group

# groupmod -n moon sun

rename a group from moon to sun

# grpck

check correct syntax and file format of


'/etc/group' and groups existence [man]

# newgrp - [group]

log into a new group to change default


group of newly created files [man]

# passwd

change password

# passwd user1

change a user password (only by root)


[man]

# pwck

check correct syntax and file format of


'/etc/passwd' and users existence [man]

# useradd -c "User Linux" -g admin


-d /home/user1 -s /bin/bash user1

create a new user "user1" belongs "admin"


group [man]

# useradd user1

create a new user

# userdel -r user1

delete a user ( '-r' eliminates home


directory) [man]

# usermod -c "User FTP" -g system -d


/ftp/user1 -s /bin/nologin user1

change user attributes

Linux Command Line: View

[man]

[man]

[man]
[man]

[man]

[man]

[man]

file content

Command

Description

# cat file1

view the contents of a file starting from the


first row [man]

# head -2 file1

view first two lines of a file

# less file1

similar to 'more' command but which allows


backward movement in the file as well as
forward movement [man]

# more file1

view content of a file along

# tac file1

view the contents of a file starting from the


last line [man]

# tail -2 file1

view last two lines of a file

[man]

[man]

[man]

# tail -f /var/log/messages

view in real time what is added to a file


[man]

Linux Command Line: YUM

packages tool (Fedora, RedHat


and alike)

Command

Description

# yum -y install [package]

download and install a rpm package

# yum localinstall [package.rpm]

That will install an RPM, and try to resolve


all the dependencies for you using your
repositories. [man]

# yum -y update

update all rpm packages installed on the


system [man]

# yum update [package]

upgrade a rpm package

# yum remove [package]

remove a rpm package

# yum list

list all packages installed on the system


[man]

# yum search [package]

find a package on rpm repository

# yum clean [package]

clean up rpm cache erasing downloaded


packages [man]

# yum clean headers

remove all files headers that the system


uses to resolve dependency [man]

# yum clean all

remove from the cache packages and


headers files [man]

[man]

[man]
[man]

[man]

Treebeard's Unix Cheat Sheet


Help on any Unix command. RTFM!
man {command}
man {command} > {filename}
whatis {command}
apropos {keyword}

Type man ls to read the manual for the


ls command.
Redirect help to a file to download.
Give short description of command.
(Not on RAIN?)
Search for all Unix commands that
match keyword, eg apropos file. (Not
on RAIN?)

List a directory
ls {path}
ls {path_1} {path_2}
ls -l {path}
ls -a {path}
ls -F {path}
ls -R {path}
ls {path} > {filename}
ls {path} | more
dir {path}

It's ok to combine attributes, eg ls -laF


gets a long listing of all files with types.
List both {path_1} and {path_2}.
Long listing, with date, size and
permisions.
Show all files, including important .dot
files that don't otherwise show.
Show type of each file. "/" = directory,
"*" = executable.
Recursive listing, with all subdirs.
Redirect directory to a file.
Show listing one screen at a time.
Useful alias for DOS people, or use
with ncftp.

Change to directory
cd {dirname}
cd ~
cd ..
cdup

There must be a space between.


Go back to home directory, useful if
you're lost.
Go back one directory.
Useful alias, like "cd ..", or use with
ncftp.

Make a new directory


mkdir {dirname}

Remove a directory
rmdir {dirname}
rm -r {dirname}

Only works if {dirname} is empty.


Remove all files and subdirs. Careful!

Print working directory


pwd

Copy a file or directory

Show where you are as full path. Useful


if you're lost or exploring.

cp {file1} {file2}
cp -r {dir1} {dir2}
cat {newfile} >> {oldfile}

Recursive, copy directory and all


subdirs.
Append newfile to end of oldfile.

Move (or rename) a file


mv {oldfile} {newfile}

Moving a file and renaming it are the


same thing.

mv {oldname} {newname}

Delete a file
rm {filespec}

ls {filespec}
rm {filespec}

Download with zmodem


sz [-a|b] {filename}
sz *.zip

Upload with zmodem


rz [-a|b] (filename}

? and * wildcards work like DOS


should. "?" is any character; "*" is any
string of characters.
Good strategy: first list a group to make
sure it's what's you think...
...then delete it all at once.
(Use sx with xmodem.)
-a = ascii, -b = binary. Use binary for
everything. (It's the default?)
Handy after downloading with FTP. Go
talk to your spouse while it does it's
stuff.
(Use rx with xmodem.)
Give rz command in Unix, THEN start
upload at home. Works fine with
multiple files.

View a text file


more {filename}
less {filename}
cat {filename}
cat {filename} | more
page {filename}
pico {filename}

View file one screen at a time.


Like more, with extra features.
View file, but it scrolls.
View file one screen at a time.
Very handy with ncftp.
Use text editor and don't save.

Edit a text file.


pico {filename}

The same editor PINE uses, so you


already know it. vi and emacs are also
available.

Create a text file.


cat > {filename}
pico {filename}

Compare two files

Enter your text (multiple lines with


enter are ok) and press control-d to
save.
Create some text and save it.

diff {file1} {file2}


sdiff {file1} {file2}

Show the differences.


Show files side by side.

Other text commands


grep '{pattern}' {file}
sort {file1} > {file2}
sort -o {file} {file}
spell {file}
wc {file}

Find regular expression in file.


Sort file1 and save as file2.
Replace file with sorted version.
Display misspelled words.
Count words in file.

Find files on system


find {filespec}
find {filespec} > {filename}

Works with wildcards. Handy for


snooping.
Redirect find list to file. Can be big!

Make an Alias
alias {name} '{command}'

Put the command in 'single quotes'.


More useful in your .cshrc file.

Wildcards and Shortcuts


*
?
[...]

~
.
..

Pipes and Redirection


{command} > {file}
{command} >> {file}
{command} < {file}
{command} < {file1} > {file2}

{command} | {command}

Permissions, important and tricky!

Match any string of characters, eg


page* gets page1, page10, and page.txt.
Match any single character, eg page?
gets page1 and page2, but not page10.
Match any characters in a range, eg
page[1-3] gets page1, page2, and
page3.
Short for your home directory, eg cd ~
will take you home, and rm -r ~ will
destroy it.
The current directory.
One directory up the tree, eg ls ...
(You pipe a command to another
command, and redirect it to a file.)
Redirect output to a file, eg ls > list.txt
writes directory to file.
Append output to an existing file, eg
cat update >> archive adds update to
end of archive.
Get input from a file, eg sort < file.txt
Get input from file1, and write to
file2, eg sort < old.txt > new.txt sorts
old.txt and saves as new.txt.
Pipe one command to another, eg ls |
more gets directory and sends it to
more to show it one page at a time.

Unix permissions concern who can read a file or directory, write to it, and execute it.
Permissions are granted or withheld with a magic 3-digit number. The three digits
correspond to the owner (you); the group (?); and the world (everyone else).
Think of each digit as a sum:
execute permission
=1
write permission
=2
write and execute (1+2)
=3
read permission
=4
read and execute (4+1)
=5
read and write (4+2)
=6
read, write and execute (4+2+1)
=7
Add the number value of the permissions you want to grant each group to make a three
digit number, one digit each for the owner, the group, and the world. Here are some
useful combinations. Try to figure them out!
You can read and write; the world can't.
chmod 600 {filespec}
Good for files.
You can read, write, and execute; the
chmod 700 {filespec}
world can't. Good for scripts.
You can read and write; the world can
chmod 644 {filespec}
only read. Good for web pages.
You can read, write, and execute; the
world can read and execute. Good for
chmod 755 {filespec}
programs you want to share, and your
public_html directory.

Permissions, another way


You can also change file permissions with letters:
u = user (yourself)
g = group
a = everyone
r = read
w = write
x = execute
chmod u+rw {filespec}
Give yourself read and write permission
chmod u+x {filespec}
Give yourself execute permission.
Give read and write permission to
chmod a+rw {filespec}
everyone.

Applications I use
finger {userid}
gopher
irc
lynx
ncftp
pico {filename}
pine

Find out what someone's up to.


Gopher.
IRC, but not available on RAIN.
Text-based Web browser, fast and lean.
Better FTP.
Easy text editor, but limited. vi and
emacs are available.
Email.

telnet {host}
tin
uudecode {filename}
uuencode {filename}
ytalk {userid}

Start Telnet session to another host.


Usenet.
Do it on the server to reduce download
size about 1/3.
Chat with someone else online, eg
ytalk mkummel. Please use w first so
you don't interrupt a big download!

System info
Show date and time.
Check system disk capacity.
Check your disk usage and show bytes
in each directory.
Read message of the day, "motd" is a
useful alias..
Show all environmental variables (in Cshell% - use set in Korn shell$).
Check your total disk use.
Find out system load.
Who's online and what are they doing?

date
df
du
more /etc/motd
printenv
quota -v
uptime
w

Unix Directory Format


Long listings (ls -l) have this format:
- file
d directory,
^
symbolic links (?)
^
^
drwxr-xr-x 11 mkummel
-rw-r--r-- 1 mkummel
^^^

^^^
^^^

* executable
file size (bytes)
file name
/ directory
^
^
^
2560 Mar 7 23:25 public_html/
10297 Mar 8 23:42 index.html
^
user permission (rwx)
date and time last modified
group permission (rwx)
world permission (rwx)

How to Make an Alias


An alias lets you type something simple and do something complex. It's a shorthand for a
command. If you want to type "dir" instead of "ls -l" then type alias dir 'ls -l'. The single
quotes tell Unix that the enclosed text is one command.
Aliases are more useful if they're permanent so you don't have to think about them. You
can do this by adding the alias to your .cshrc file so they're automatically loaded when
you start. Type pico .cshrc and look for the alias section and add what you want. It will
be effective when you start. Just remember that if you make an alias with the name of a
Unix command, that command will become unavailable.
Here are a few aliases from my .cshrc file:

# enter your aliases here in the form:


# alias
this
means this
alias
alias
alias
alias
alias
alias
alias
alias

h
m

bye
ls
dir
cdup
motd

history
more
quota -v
exit
ls -F
ls
cd ..
more /etc/motd

How to Make a Script


A Unix script is a text file of commands that can be executed, like a .bat file in DOS.
Unix contains a powerful programming language with loops and variables that I don't
really understand. Here's a useful example.
Unix can't rename a bunch of files at once the way DOS can. This is a problem if you
develop Web pages on a DOS machine and then upload them to your Unix Server. You
might have a bunch of .htm files that you want to rename as .html files, but Unix makes
you do it one by one. This is actually not a defect. (It's a feature!) Unix is just being more
consistent than DOS. So make a script!
Make a text file (eg with pico) with the following lines. The first line is special. It tells
Unix what program or shell should execute the script. Other # lines are comments.
#! /bin/csh
# htm2html converts *.htm files to *.html
foreach f ( *.htm )
set base=`basename $f .htm`
mv $f $base.html
end

Save this in your home directory as htm2html (or whatever). Then make it userexecutable by typing chmod 700 htm2html. After this a * will appear by the file name
when you ls -F, to show that it's executable. Change to a directory with .htm files and
type ~/htm2html, and it will do its stuff.
Think about scripts whenever you find yourself doing the same tedious thing over and
over.

Dotfiles (aka Hidden Files)


Dotfile names begin with a "." These files and directories don't show up when you list a
directory unless you use the -a option, so they are also called hidden files. Type ls -la in
your home directory to see what you have.

Some of these dotfiles are crucial. They initialize your shell and the programs you use,
like autoexec.bat in DOS and .ini files in Windows. rc means "run commands". These
are all text files that can be edited, but change them at your peril. Make backups first!
Here's some of what I get when I type ls -laF:
.addressbook
.cshrc
.gopherrc
.history
.login
.lynxrc
.ncftp/
.newsrc
.pinerc
.plan
.profile
.project
.signature
.tin/
.ytalkrc

my email addressbook.
my C-shell startup info, important!
my gopher setup.
list of past commands.
login init, important!
my lynx setup for WWW.
hidden dir of ncftp stuff.
my list of subscribed newsgroups.
my pine setup for email.
text appears when I'm fingered, ok to edit.
Korn shell startup info, important!
text appears when I'm fingered, ok to edit.
my signature file for mail and news, ok to edit.
hidden dir of my tin stuff for usenet.
my ytalk setup.

DOS and UNIX commands


Action
change directory
change file protection
compare files
copy file
delete file
delete directory
directory list
edit a file
environment
find string in file
help
make directory
move file
rename file
show date and time
show disk space
show file
show file by screens
sort data

DOS
cd
attrib
comp
copy
del
rd
dir
edit
set
find
help
md
move
ren
date, time
chkdsk
type
type filename | more
sort

UNIX
cd
chmod
diff
cp
rm
rmdir
ls
pico
printenv
grep
man
mkdir
mv
mv
date
df
cat
more
sort

Linux Commands
A B C D E F G H I K L M N P Q R S T U V W XYZ
References and answers
back to beginning
A
alias Create your own name for a command
arch print machine architecture
ash ash command interpreter (shell)
awk (gawk) pattern scanning and processing language
B
basename Remove directory and suffix from a file name
bash GNU Bourne-Again Shell
bsh Command interpreter (Shell)
bc Command line calculator
bunzip2 Unzip .bz2 files
C back to commands top
cat Concatenate a file print it to the screen
chgrp Change the group designation of a file
chmod Change file permissions
chown Change the owner of a file
cjpeg Compress an image file to a JPEG file
clear Clear terminal screen (command line)
comm Compare two sorted files
stty cooked Formatting the display of text in a terminal
cp Copy command
cpio Copy files to and from archives
csh C Shell
cut Print selected parts of lines to standard output
D back to commands top
date Display date and time
dc Command line calculator
df Show amount of disk space free
diff Determine difference between two files
diff3 Determine difference between 3 files
dig Interrogate DNS name servers
djpeg Decompress a JPEG file to an image file
dmesg Print or control the kernel ring buffer (print out bootup messages)

dnsdomainname Show the system's DNS domain name


doexec Run an executable with an arbitrary argv
domainname Show or set the system's NIS/YP domain name
dos2unix Converts plain text files in DOS/MAC format to UNIX format
du Show disk useage
dumpkeys Write keyboard driver's translation tables to std output
E back to commands top
echo Display a line of text
ed Line-oriented text editor
egrep Print lines matching a pattern
elinks A text mode WWW browser (supports frames)
env Dislay the path
ex Start Vim in ex mode
eject Eject media from device ( command line )
F back to commands top
factor Display prime factors of a number
false Exit with a status code indicating failure
fdisk The fdisk command with usage examples
fgrep Variant of grep
find Find a file
finger Displays information about the system users
fixps Try to fix common PostScript problems that break postprocessing
free Display free memory
G back to commands top
grep Search for a pattern using regular expression
gtar See the tar command
gunzip Unzip .gz files
gzip Compress using Lempel-Ziv coding (LZ77)
H back to commands top
halt Stop the system
hdparm Get/set harddisk parameters
head Print the first 10 lines of a file to standard output
hostname Show or set the system's host name
history Display entire command history
HISTSIZE Change history size
httpd Start Apache

I back to commands top


identify Describes the format and characteristics of image files.
id Print information for username, or the current user
ifconfig Display network and hardware addresses
igawk Gawk with include files
ipcalc Calculate IP information for a host
K back to commands top
kbd_mode Report or set the keyboard mode (RAW, MEDI- UMRAW or XLATE)
kill Terminate a process
L back to commands top
last Show listing of last logged in users
lastlog Formats and prints the contents of the last login log /var/log/lastlog file
link Call the link function to create a link to a file
links See elinks
ln Create a link to the specified TARGET with optional LINK_NAME
loadkeys Load keyboard translation tables
locate Locate a file
login Sign on
look Displays any lines in file which contain "string" as a prefix.
ls List directory contents
lsmod List loaded kernel modules
lynx Command to start the Lynx browser
M back to commands top
mac2unix Converts plain text files in DOS/MAC format to UNIX format
mail A mail processing system, which has a command syntax like ed
man Display a particular manual entry
manweb Manweb is part of the Netpbm package
mdu Display the amount of space occupied by an MSDOS directory
mkdir Create a directory
mkfs Make a filesystem on a drive
mknod Make block or character special files
mktemp Make temporary filename (unique)
more Page through text one screenful at a time.
mount Mount a filesystem/device
mt Control magnetic tape drive operation
mv Move and / or rename files
:

N
namei Follow a pathname until a terminal point is found
nano An enhanced free Pico clone
nc arbitrary TCP and UDP connections and listens
(note that nc is also called the client interface
to the NEdit program but it is not the
command that invokes nedit-nc on current systems)
ncftp Browser program for the File Transfer Protocol
nedit-nc nedit-nc is the client interface to the NEdit text editor
netstat Display verbose info about network processes and ports
nice Run a command with modified priority
nisdomainname Show or set system's NIS/YP domain name
nslookup query internet domain name servers
P
paste Merge lines of files
pdf2dsc Generate a PostScript page list of a PDF document
pdf2ps Convert PDF file "input.pdf" to PostScript(tm) in "output.ps"
pdfinfo Print contents of the 'Info' dictionary (plus some other useful information) from
a PDF file
pdftotext Convert pdf files to plain text
perl (start) Practical Extraction and Report Language
pgawk The profiling version of gawk
pico Text editor that comes with Pine (from the University of Washington)
pine Email program used by The University of Washington
ping6 Ping
ping Send ICMP ECHO_REQUEST to network hosts
pinky A lightweight 'finger' program;
pr Format for printing
ps Processes running
ps2ascii Ghostscript translator from PostScript or PDF to ASCII
ps2epsi Generate conforming Encapsulated PostScript
ps2frag Obsolete shell script for the PSfrag system
ps2pdf12 Convert PostScript to PDF 1.2 (Acrobat 3 and later compatible) using
ghostscript
ps2pdf13 Convert PostScript to PDF 1.3 (Acrobat 4 and later compatible) using
ghostscript
ps2pdf14 Use ps2pdfwr: Convert PostScript to PDF without specifying Compatibility
Level, using ghostscript
ps2pdf Convert PostScript to PDF using ghostscript
ps2pdfwr Convert PostScript to PDF without specifying Compatibility Level, using
ghostscript
ps2pk creates a TeX pkfont from a type1 PostScript font
ps2ps ps2ps uses gs to convert PostScript(tm) file "input.ps" to simpler and (usually)
faster PostScript in "output.ps"

psbook Rearranges pages from a PostScript document into "signatures" for printing
books or booklets
pwd Print Working Directory
Q back to commands top
quota display disk usage and limits
R back to commands top
resize Xterm window size
readelf Displays information about ELF files
reboot Stop the system, poweroff, reboot
red red is a restricted ed: it can only edit files in the current directory and cannot
execute shell commands
rename Rename files
rmdir Remove a directory
rm Remove files or directories
rpm rpm command options
rundig Sample script to create a search database for ht://Dig
rview The GUI version of Vim in easy mode with restrictions
rvi Vi / Vim editor
S back to commands top
sed Stream editor
setfont Load EGA/VGA console screen font
set gid Set group id
set serial Get / set Linux serial port info
set uid Set user id
sfdisk Modified fdisk program
sftp Secure file transfer protocol (ftp)
sh Shell (BASH)
shred Safely remove data from disk drive
sleep Delay for a specified amount of time
slocate Security Enhanced version of the GNU Locate
sort Sort lines of a text file
ssh Secure shell connection command
stty change and print terminal line settings
stty raw Unformatted output to terminal
su Become super user ( root )
switchdesk Graphical and text mode interface for choosing desktop environment
sync Force changed blocks to disk, update the super block
ssh Secure shell connection command

T back to commands top


tail Print the last 10 Lines of a file standard output
tar Create an Archive
tcsh Enhanced completely compatible version of the Berkeley UNIX C shell, csh
tee Copy standard input to each file, and also to standard output
telnet User interface to the telnet protocol
time Run the specified program command with the given arguments
touch Change file timestamps
tracepath6 See tracepath
tracepath Trace path to a network host discovering MTU along this path
traceroute6 See traceroute
traceroute Print the route packets take to network host
tree Display file tree
true Exit with a status code indicating success
tty Print name of terminal connected to standard output
U back to commands top
umask File creation mask / Bash builtins
umount Detache file system(s) mentioned from file hierarchy
uname Print system information ( kernel version )
unicode_start Put keyboard and console into Unicode (UTF-8) mode
unicode_stop Undo the effect of unicode_start
unlink Call the unlink function to remove the specified file
uniq Remove duplicate lines from sorted file
updatedb Update the slocate database
unset gid Group id change
unset uid User id change
untar Unarchive ( untar ) a file
unzip Unzip .zip files
useradd Add new user
users Output who is currently logged in according to system records
usleep Sleep a given number of microseconds. default is 1
V back to commands top
view Start vim in read-only mode
vi Start the vi editor
W back to commands top
w Show who is logged on and what they are doing
wc Word count of a file
wget Non-interactive download of files from the Web
whatis Search the whatis database for complete words (command names)
whereis Locate a command or file

which Find command path


whoami Print effective userid
who show who is logged on
whois Client for the whois service
X,Y,Z back to commands top
xinit Start Xserver
xpdf Portable Document Format (PDF) file viewer for X windows
xrandr Change resolution running Xwindows ( command line )
ypdomainname show or set the system's NIS/YP domain name
zcat Compress or expand files
zip Compression and file packaging utility for Unix, VMS, MSDOS, OS/2, Windows NT,
Minix,
Atari and Macintosh, Amiga and Acorn RISC OS. It is analogous to a
combination of the UNIX commands tar(1) and compress(1) and is
compatible with PKZIP (Phil Katzs ZIP for MSDOS
systems)
zipinfo List detailed information about a ZIP archive

You might also like