42
Linux Commands There are of course thousands of Linux related commands and procedures. I will give a few of the more common ones here but I assure you there is A LOT more to Linux than just these relatively simple commands. A few tips with Linux type man command to get an extensive help file. For example type 'man ls' to get the manual page for the ls command containing information on the various switches and uses of the ls command. You can also execute multiple commands by separating each one with a ; for example cd newdir; mkdir thatdir ; ls -la will first change directories to the newdir directory, then create a directory called thatdir, then list all the files in long format. You can string together as many commands as you like but caution should be used not to inadvertently do anything harmful. Contents (Select the command to go to the relevant section select BACK TO CONTENTS to get back here) cd chmod cp df dir du find head kill less ls mkdir more mv ps pwd rm rmdir tail top tree vdir vi xload cd This command is used to ch ange the d irectory and using this command will change your location to what ever directory you specify cd hello will change to the directory named hello located inside the current directory cd /home/games will change to the directory called games within the home directory. As you can see you can specify any directory on the Linux system and change to that directory from any other directory. There are of course a variety of switches associated with the cd command but generally it is used pretty much as it is. Type man cd for more information on the cd command. See also ls dir vdir BACK TO CONTENTS chmod This command is used to ch ange the mod e for files to know more about this command go to the Permissions (Setting up the mode)section. You can get there by using this link chmod you will need to use the back button (or go through the linux home page menu) on your browser to get back here). cp The cp command copies files. You can copy a file in within the current directory or you can copy files to another directory. cp myfile.html /home/help/mynewname.html This will copy the file called myfile.html in the current directory to the directory

20628549 Linux Commands

  • Upload
    gajasam

  • View
    37

  • Download
    5

Embed Size (px)

Citation preview

Page 1: 20628549 Linux Commands

Linux CommandsThere are of course thousands of Linux related commands and procedures. I will give a few of the more common ones here but I assure you there is A LOT more to Linux than just these relatively simple commands. A few tips with Linux type man command to get an extensive help file. For example type 'man ls' to get the manual page for the ls command containing information on the various switches and uses of the ls command. You can also execute multiple commands by separating each one with a ; for example cd newdir; mkdir thatdir ; ls -la will first change directories to the newdir directory, then create a directory called thatdir, then list all the files in long format. You can string together as many commands as you like but caution should be used not to inadvertently do anything harmful. Contents (Select the command to go to the relevant section select BACK TO CONTENTS to get back here)

cd chmod cp df dir du find head kill less ls mkdir more mv ps pwd rmrmdir tail top tree vdir vi xload

cd This command is used to change the directory and using this command will change your location to what ever directory you specify cd hello will change to the directory named hello located inside the current directory cd /home/games will change to the directory called games within the home directory. As you can see you can specify any directory on the Linux system and change to that directory from any other directory. There are of course a variety of switches associated with the cd command but generally it is used pretty much as it is. Type man cd for more information on the cd command. See also ls dir vdir BACK TO CONTENTS

chmod This command is used to change the mode for files to know more about this command go to the Permissions (Setting up the mode)section. You can get there by using this link chmod you will need to use the back button (or go through the linux home page menu) on your browser to get back here).

cp The cp command copies files. You can copy a file in within the current directory or you can copy files to another directory. cp myfile.html /home/help/mynewname.html This will copy the file called myfile.html in the current directory to the directory

Page 2: 20628549 Linux Commands

/home/help/ and call it mynewname.html. Simply put the cp command has the format of cp file1 file2 With file1 being the name (including the path if needed) of the file being copied and file2 is the name (including the path if needed) of the new file being created. Remember with the cp command the original file remains in place. Type man cp to see more about the cp command. BACK TO CONTENTS

df The disk free command shows how much memory is being used and how much is free for every partition and mounted file system (including any Windows drive/s). Type man df for more information about the df command. BACK TO CONTENTS

dir The dir command is similar to the ls command only with less available switches (only about 50 compared to about 80 for ls). By using the dir command you will get a listing of the contents in the current directory listed in columns. Type man dir to see more about the dir command. See also cd ls vdir BACK TO CONTENTS

du The disk usage command shows how much memory is being used by each directory below that from which the command was given. If du is run from the root directory it will show the memory used by every directory on the system, including any mounted file systems (including other drives) such as any Windows related drives. Type man du for more information about the du command. BACK TO CONTENTS

find The find command is used to find files and or folders within a Linux system. To find a file using the find command you type find /usr/bin -name filename this will search inside the /usr/bin directory (and any sub directories within the /usr/bin directory) for the file named filename. To search the entire filing system including any mounted drives use find / -name filename and the find command will search every file system beginning in the root directory. The find command can also be used to find command to find files by date and the find command happily understand wild characters such as * and ? Type man find for more information on the find command. BACK TO CONTENTS

Page 3: 20628549 Linux Commands

head The head command list the first lines of a file. By default it will display the first ten lines of a file. For example head filename will list the first ten lines of the file named filename. You can also select how many lines to show for example head -5 filename will list the first 5 lines of the file named filename. The format for the head command is head -n filename With the number of lines to be displayed being n and the file name of the file, including the path if needed, you wish to view being in place of filename. Type man head for more information on the head command. BACK TO CONTENTS

kill The kill command is used to kill a process by using the associated PID (Process ID) number e.g. kill 381 This will kill the process with the PID of 381. Be careful using the kill command because it is easy to accidently kill an important process. To see the current list of processes that are running use the ps command. Typing ps au will display every process that is in operation including background processes and those being conducted by other users. See also ps top BACK TO CONTENTS

less This command allows you to scroll through a file a page at a time. The less command is very similar to the more command only it is more advanced and has more features associated with it. less filename Type man less for more information on the less command. BACK TO CONTENTS

ls The ls command lists the contents of a directory. In its simple form typing just ls at the command prompt will give a listing for the directory you are currently in. The ls command can also give listings of other directories without having to go to those directories for example typing ls /dev/bin will display the listing for the directory /dev/bin . The ls command can also be used to list specific files by typing ls filename this will display the file filename (of course you can use any file name here). The ls command can also handle wild characters such as the * and ? . For example ls a* will list all files

Page 4: 20628549 Linux Commands

starting with lower case a ls [aA]* will list files starting with either lower or upper case a (a or A remember linux is case sensitive) or ls a? will list all two character file names beginning with lower case a . There are many switches (over 70) associated with the ls command that perform specific functions. Some of the more common switches are listed here.

• ls -a This will list all file including those beginning with the'.' that would normally be hidden from view.

• ls -l This gives a long listing showing file attributes and file permissions. • ls -s Will display the listing showing the size of each file rounded up to the

nearest kilobyte. • ls -S This will list the files according to file size. • ls -C Gives the listing display in columns. • ls -F Gives a symbol next to each file in the listing showing the file type. The /

means it is a directory, the * means an executable file, the @ means a symbolic link.

• ls -r Gives the listing in reverse order. • ls -R This gives a recursive listing of all directories below that where the

command was issued. • ls -t Lists the directory according to time stamps.

Switches can be combined to produce any output you desire. e.g. ls -la This will list all the files in long format showing full file details.

Type man ls for more details about the ls command. See also cd dir vdir BACK TO CONTENTS

mkdir The mkdir command is used to create a new directory. mkdir mydir This will make a directory (actually a sub directory) within the current directory called mydir. Type man mkdir to see more about the mkdir command. BACK TO CONTENTS

more This command allows you too scroll through a file one screen at a time allowing you to more easily read the files contents. Some files are very big and using this command allows you to view the contents of large files more efficiently. To go forward one screen use the space bar and to go back one screen use the B key more filename

Page 5: 20628549 Linux Commands

Type man more for more information about the more command. BACK TO CONTENTS

mv The mv command moves files from one location to another. With the mv command the file will be moved an no longer exist in its former location prior to the mv. The mv command can also be used to rename files. You can move files within the current directory or another directory. cp myfile.html /home/help/mynewname.html This will move the file called myfile.html in the current directory to the directory /home/help/ and call it mynewname.html. Simply put the mv command has the format of mv file1 file2 With file1 being the name (including the path if needed) of the file being moved and file2 is the name (including the path if needed) of the new file being created. Type man mv to see more about the mv command. BACK TO CONTENTS

ps The ps (process status) will by default only show the processes that you as a user have started. However Linux is always running background tasks so you may want to use some of the common switches associated with the ps such as ps au to display the processes running for all users and in the user format hence we get to see every process that is running on the system. When a process is started it is given among other things a PID number that is unique to it. This PID number can be seen by using the ps command or top command. By knowing a Process ID number you may opt to kill the process if you choose. See also kill top BACK TO CONTENTS

pwd The pwd command (print working directory) will display the current directory. e.g. typing pwd will display something similar to this /home/games/help being the details of the current directory. To get help with the pwd type /bin/pwd --help and a short help file will be displayed. Type man pwd to get more information about the pwd command. BACK TO CONTENTS

rm The rm command is used to delete files. Some very powerful switches can be used with the rm command so be sure to check the man rm file before placing extra switches on the rm command.

Page 6: 20628549 Linux Commands

rm myfile This will delete the file called mydir. You can include a path to delete a file in another directory for example rm /home/hello/goodbye.htm will delete the file named goodbye.htm in the directory /home/hello/. Some of the common switches for the rm command are

• rm -i this operates the rm command in interactive mode meaning it will prompt you before deleting a file. This gives you a second chance to say no do not delete the file or yes delete the file. Remember Linux is merciless and once something is deleted it is gone for good so the -i flag (switch) is a good one to get into the habit of using.

• rm -f will force bypassing any safeguards that may be in place such as prompting. Again this command is handy to know but care should be taken with its use.

• rm -r will delete every file and sub directory below that in which the command was given. Be very careful with this command as no prompt will be given in most linux systems and it will mean instant good bye to your files if misused.

Type man rm to see more about the rm command. BACK TO CONTENTS

rmdir The rmdir command is used to delete a directory. rmdir mydir This will delete the directory (actually a sub directory) called mydir. Type man rmdir to see more about the rmdir command. BACK TO CONTENTS

tail The tail command list the last lines of a file. By default it will display the last ten lines of a file. For example tail filename will list the last ten lines of the file named filename. You can also select how many lines to show for example tail -5 filename will list the last 5 lines of the file named filename. The format for the tail command is tail -n filename With the number of lines to be displayed being n and the file name of the file you wish to view, including the path if needed, being in place of filename. Type man tail for more information on the tail command. BACK TO CONTENTS

top Either typing top at the command prompt or selecting top from the xwindows menu will activate the top application. Top simply lists all the operations in progress showing

Page 7: 20628549 Linux Commands

memory usage by each process. You have the option to kill any process if you want to but be careful if you kill a vital system you will run into trouble and may at the very least have to reboot to fix it. Typically top is run in a spare xterm or x11 window while doing other tasks. To access the help in top use the ? or H key. To kill a task use the K key or change the priority of the task by using the R key. Type man top to see more detailed information about the top command. see also xload BACK TO CONTENTS

tree This will give a graphical display of the structure of a particular directory and all sub directories, files and links within that directory. e.g. tree /var/lib will show something similar to this

/var/lib |--games |--rpm | |--conflictsindex.rpm | |--fileindex.rpm | |--groupsindex.rpm | |--packages.rpm | `--require.rpm `--text

6 directories, 6 files

Type man tree for more information on the tree command. BACK TO CONTENTS

vdir The vdir command is similar to the ls -l command. When used the command acts very much like ls -l does by displaying the directory contents showing the file attributes and permissions. The amount of switches for vdir are a lot less than for the ls command (vdir has just over half the amount of available switches as the ls command) but vdir is still used and accepted.

Type man vdir to see more about the vdir command. See also cd dir ls BACK TO CONTENTS

vi The vi command is actually a text editor that comes as standard with most Linux

Page 8: 20628549 Linux Commands

packages. Type man vi for more information on vi. More information on vi is in the Using the vi Editor section. Use this link vi to get there . BACK TO CONTENTS

xload Either typing xload or selecting xload from the xwindows menu (if it is available) will activate the xload feature in a x11 window. The xload application provides a running graph of the system load. Often it is easier to tell if a system is overloaded by having a visual aid to see the load on the system. The xload command has eight different command line options and can be customized in regards to colour, scale and background. Typically xload is run as a background task to enable visual monitoring of the system load. Type man xload to see more detailed information about the xload command. see also top BACK TO CONTENTS

Command Description• apropos whatis Show commands pertinent to string. See also threadsafe• man -t man | ps2pdf - > man.pdf make a pdf of a manual page which command Show full path name of command time command See how long a command takes• time cat Start stopwatch. Ctrl-d to stop. See also sw

• nice infoRun a low priority command (The "info" reader in this case)

• renice 19 -p $$Make shell (script) low priority. Use for non interactive tasks

dir navigation• cd - Go to previous directory• cd Go to $HOME directory (cd dir && command) Go to dir, execute command and return to current dir• pushd . Put current dir on stack so you can popd back to it

Page 9: 20628549 Linux Commands

file searching• alias l='ls -l --color=auto' quick dir listing• ls -lrt List files by date. See also newest and find_mm_yyyy• ls /usr/bin | pr -T9 -W$COLUMNS Print in 9 columns to width of terminal find -name '*.[ch]' | xargs grep -E 'expr' Search 'expr' in this dir and below. See also findrepo find -type f -print0 | xargs -r0 grep -F 'example' Search all regular files for 'example' in this dir and below find -maxdepth 1 -type f | xargs grep -F 'example' Search all regular files for 'example' in this dir

find -maxdepth 1 -type d | while read dir; do echo $dir; echo cmd2; done

Process each item with multiple commands (in while loop)

• find -type f ! -perm -444 Find files not readable by all (useful for web site)• find -type d ! -perm -111 Find dirs not accessible by all (useful for web site)

• locate -r 'file[^/]*\.txt'Search cached index for names. This re is like glob *file*.txt

• look reference Quickly search (sorted) dictionary for prefix• grep --color reference /usr/share/dict/words Highlight occurances of regular expression in dictionaryarchives and compression gpg -c file Encrypt file gpg file.gpg Decrypt file tar -c dir/ | bzip2 > dir.tar.bz2 Make compressed archive of dir/ bzip2 -dc dir.tar.bz2 | tar -x Extract archive (use gzip instead of bzip2 for tar.gz files)

tar -c dir/ | gzip | gpg -c | ssh user@remote 'dd of=dir.tar.gz.gpg'

Make encrypted archive of dir/ on remote machine

find dir/ -name '*.txt' | tar -c --files-from=- | bzip2 > dir_txt.tar.bz2

Make archive of subset of dir/ and below

find dir/ -name '*.txt' | xargs cp -a --target-directory=dir_txt/ --parents

Make copy of subset of dir/ and below

( tar -c /dir/to/copy ) | ( cd /where/to/ && tar -x -p ) Copy (with permissions) copy/ dir to /where/to/ dir

( cd /dir/to/copy && tar -c . ) | ( cd /where/to/ && tar -x -p )

Copy (with permissions) contents of copy/ dir to /where/to/

( tar -c /dir/to/copy ) | ssh -C user@remote 'cd /where/to/ && tar -x -p'

Copy (with permissions) copy/ dir to remote:/where/to/ dir

dd bs=1M if=/dev/sda | gzip | ssh user@remote 'dd of=sda.gz'

Backup harddisk to remote machine

rsync (Network efficient file copier: Use the --dry-run option for testing)

rsync -P rsync://rsync.server.com/path/to/file fileOnly get diffs. Do multiple times for troublesome downloads

rsync --bwlimit=1000 fromfile tofile Locally copy with rate limit. It's like nice for I/O

rsync -az -e ssh --delete ~/public_html/ remote.com:'~/public_html'

Mirror web site (using compression and encryption)

rsync -auz -e ssh remote:/dir/ . && rsync -auz -e ssh . remote:/dir/

Synchronize current directory with remote one

ssh (Secure SHell)

ssh $USER@$HOST commandRun command on $HOST as $USER (default command=shell)

Page 10: 20628549 Linux Commands

• ssh -f -Y $USER@$HOSTNAME xeyes Run GUI command on $HOSTNAME as $USER

scp -p -r $USER@$HOST: file dir/Copy with permissions to $USER's home directory on $HOST

ssh -g -L 8080:localhost:80 root@$HOSTForward connections to $HOSTNAME:8080 out to $HOST:80

ssh -R 1434:imap:143 root@$HOST Forward connections from $HOST:1434 in to imap:143wget (multi purpose download tool)

•(cd dir/ && wget -nd -pHEKk http://www.pixelbeat.org/cmdline.html)

Store local browsable version of a page to the current dir

wget -c http://www.example.com/large.file Continue downloading a partially downloaded file

wget -r -nd -np -l1 -A '*.jpg' http://www.example.com/dir/

Download a set of files to the current directory

wget ftp://remote/file[1-9].iso/ FTP supports globbing directly

•wget -q -O- http://www.pixelbeat.org/timeline.html | grep 'a href' | head

Process output directly

echo 'wget url' | at 01:00 Download url at 1AM to current dir wget --limit-rate=20k url Do a low priority download (limit to 20KB/s in this case) wget -nv --spider --force-html -i bookmarks.html Check links in a file wget --mirror http://www.example.com/ Efficiently update a local copy of a site (handy from cron)networking (Note ifconfig, route, mii-tool, nslookup commands are obsolete) ethtool eth0 Show status of ethernet interface eth0 ethtool --change eth0 autoneg off speed 100 duplex full Manually set ethernet interface speed iwconfig eth1 Show status of wireless interface eth1 iwconfig eth1 rate 1Mb/s fixed Manually set wireless interface speed• iwlist scan List wireless networks in range• ip link show List network interfaces ip link set dev eth0 name wan Rename interface eth0 to wan ip link set dev eth0 up Bring interface eth0 up (or down)• ip addr show List addresses for interfaces ip addr add 1.2.3.4/24 brd + dev eth0 Add (or del) ip and mask (255.255.255.0)• ip route show List routing table ip route add default via 1.2.3.254 Set default gateway to 1.2.3.254• tc qdisc add dev lo root handle 1:0 netem delay 20msec Add 20ms latency to loopback device (for testing)• tc qdisc del dev lo root Remove latency added above• host pixelbeat.org Lookup DNS ip address for name or vice versa• hostname -i Lookup local ip address (equivalent to host `hostname`)• whois pixelbeat.org Lookup whois info for hostname or ip address• netstat -tupl List internet services on a system• netstat -tup List active connections to/from systemwindows networking (Note samba is the package that provides all this windows specific networking support)• smbtree Find windows machines. See also findsmb

nmblookup -A 1.2.3.4Find the windows (netbios) name associated with ip address

smbclient -L windows_box List shares on windows machine or samba server

Page 11: 20628549 Linux Commands

mount -t smbfs -o fmask=666,guest //windows_box/share /mnt/share

Mount a windows share

echo 'message' | smbclient -M windows_boxSend popup to windows machine (off by default in XP sp2)

text manipulation (Note sed uses stdin and stdout. Newer versions support inplace editing with the -i option) sed 's/string1/string2/g' Replace string1 with string2 sed 's/\(.*\)1/\12/g' Modify anystring1 to anystring2 sed '/ *#/d; /^ *$/d' Remove comments and blank lines sed ':a; /\\$/N; s/\\\n//; ta' Concatenate lines with trailing \ sed 's/[ \t]*$//' Remove trailing spaces from lines sed 's/\([`"$\]\)/\\\1/g' Escape shell metacharacters active within double quotes• seq 10 | sed "s/^/ /; s/ *\(.\{7,\}\)/\1/" Right align numbers sed -n '1000p;1000q' Print 1000th line sed -n '10,20p;20q' Print lines 10 to 20 sed -n 's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q' Extract title from HTML web page sed -i 42d ~/.ssh/known_hosts Delete a particular line sort -t. -k1,1n -k2,2n -k3,3n -k4,4n Sort IPV4 ip addresses• echo 'Test' | tr '[:lower:]' '[:upper:]' Case conversion• tr -dc '[:print:]' < /dev/urandom Filter non printable characters• history | wc -l Count linesset operations (Note you can export LANG=C for speed. Also these assume no duplicate lines within a file) sort file1 file2 | uniq Union of unsorted files sort file1 file2 | uniq -d Intersection of unsorted files sort file1 file1 file2 | uniq -u Difference of unsorted files sort file1 file2 | uniq -u Symmetric Difference of unsorted files join -a1 -a2 file1 file2 Union of sorted files join file1 file2 Intersection of sorted files join -v2 file1 file2 Difference of sorted files join -v1 -v2 file1 file2 Symmetric Difference of sorted filesmath• echo '(1 + sqrt(5))/2' | bc -l Quick math (Calculate φ). See also bc• echo 'pad=20; min=64; (100*10^6)/((pad+min)*8)' | bc More complex (int) e.g. This shows max FastE packet rate

•echo 'pad=20; min=64; print (100E6)/((pad+min)*8)' | python

Python handles scientific notation

•echo 'pad=20; plot [64:1518] (100*10**6)/((pad+x)*8)' | gnuplot -persist

Plot FastE packet rate vs packet size

• echo 'obase=16; ibase=10; 64206' | bc Base conversion (decimal to hexadecimal)

• echo $((0x2dec))Base conversion (hex to dec) ((shell arithmetic expansion))

• units -t '100m/9.69s' 'miles/hour' Unit conversion (metric to imperial)• units -t '500GB' 'GiB' Unit conversion (SI to IEC prefixes)• units -t '1 googol' Definition lookup• seq 100 | (tr '\n' +; echo 0) | bc Add a column of numbers. See also add and funcpycalendar

Page 12: 20628549 Linux Commands

• cal -3 Display a calendar• cal 9 1752 Display a calendar for a particular month year• date -d fri What date is it this friday. See also day• [ $(date -d "tomorrow" +%d) = "01" ] || exit exit a script unless it's the last day of the month• date --date='25 Dec' +%A What day does xmas fall on, this year

• date --date='@2147483647'Convert seconds since the epoch (1970-01-01 UTC) to date

• TZ=':America/Los_Angeles' dateWhat time is it on West coast of US (use tzselect to find TZ)

echo "mail -s 'get the train' [email protected] < /dev/null" | at 17:45

Email reminder

•echo "DISPLAY=$DISPLAY xmessage cooker" | at "NOW + 30 minutes"

Popup reminder

locales

• printf "%'d\n" 1234Print number with thousands grouping appropriate to locale

• BLOCK_SIZE=\'1 ls -l get ls to do thousands grouping appropriate to locale• echo "I live in `locale territory`" Extract info from locale database• LANG=en_IE.utf8 locale int_prefix Lookup locale info for specific country. See also ccodes• locale | cut -d= -f1 | xargs locale -kc | less List fields available in locale databaserecode (Obsoletes iconv, dos2unix, unix2dos)• recode -l | less Show available conversions (aliases on each line)

recode windows-1252.. file_to_change.txtWindows "ansi" to local charset (auto does CRLF conversion)

recode utf-8/CRLF.. file_to_change.txt Windows utf8 to local charset recode iso-8859-15..utf8 file_to_change.txt Latin9 (western europe) to utf8 recode ../b64 < file.txt > file.b64 Base64 encode recode /qp.. < file.txt > file.qp Quoted printable decode recode ..HTML < file.txt > file.html Text to HTML• recode -lf windows-1252 | grep euro Lookup table of characters• echo -n 0x80 | recode latin-9/x1..dump Show what a code represents in latin-9 charmap• echo -n 0x20AC | recode ucs-2/x2..latin-9/x Show latin-9 encoding• echo -n 0x20AC | recode ucs-2/x2..utf-8/x Show utf-8 encodingCDs gzip < /dev/cdrom > cdrom.iso.gz Save copy of data cdrom mkisofs -V LABEL -r dir | gzip > cdrom.iso.gz Create cdrom image from contents of dir mount -o loop cdrom.iso /mnt/dir Mount the cdrom image at /mnt/dir (read only) cdrecord -v dev=/dev/cdrom blank=fast Clear a CDRW

gzip -dc cdrom.iso.gz | cdrecord -v dev=/dev/cdrom -Burn cdrom image (use dev=ATAPI -scanbus to confirm dev)

cdparanoia -B Rip audio tracks from CD to wav files in current dir

cdrecord -v dev=/dev/cdrom -audio *.wavMake audio CD from all wavs in current dir (see also cdrdao)

oggenc --tracknum='track' track.cdda.wav -o 'track.ogg' Make ogg file from wav file

Page 13: 20628549 Linux Commands

disk space (See also FSlint)• ls -lSr Show files by size, biggest last• du -s * | sort -k1,1rn | head Show top disk users in current dir. See also dutop• df -h Show free space on mounted filesystems• df -i Show free inodes on mounted filesystems• fdisk -l Show disks partitions sizes and types (run as root)• rpm -q -a --qf '%10{SIZE}\t%{NAME}\n' | sort -k1,1n List all packages by installed size (Bytes) on rpm distros

•dpkg-query -W -f='${Installed-Size;10}\t${Package}\n' | sort -k1,1n

List all packages by installed size (KBytes) on deb distros

• dd bs=1 seek=2TB if=/dev/null of=ext3.test Create a large test file (taking no space). See also truncate• > file truncate data of file or create an empty filemonitoring/debugging• tail -f /var/log/messages Monitor messages in a log file• strace -c ls >/dev/null Summarise/profile system calls made by command• strace -f -e open ls >/dev/null List system calls made by command• ltrace -f -e getenv ls >/dev/null List library calls made by command• lsof -p $$ List paths that process id has open• lsof ~ List processes that have specified path open

• tcpdump not port 22Show network traffic except ssh. See also tcpdump_not_me

• ps -e -o pid,args --forest List processes in a hierarchy

•ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | sed '/^ 0.0 /d'

List processes by % cpu usage

• ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS List processes by mem usage. See also ps_mem.py• ps -C firefox-bin -L -o pid,tid,pcpu,state List all threads for a particular process• ps -p 1,2 List info for particular process IDs• last reboot Show system reboot history• free -m Show amount of (remaining) RAM (-m displays in MB)• watch -n.1 'cat /proc/interrupts' Watch changeable data continuouslysystem information (see also sysinfo) ('#' means root access is required)• uname -a Show kernel version and system architecture• head -n1 /etc/issue Show name and version of distribution• cat /proc/partitions Show all partitions registered on the system• grep MemTotal /proc/meminfo Show RAM total seen by the system• grep "model name" /proc/cpuinfo Show CPU(s) info• lspci -tv Show PCI info• lsusb -tv Show USB info• mount | column -t List mounted filesystems on the system (and align output)• grep -F capacity: /proc/acpi/battery/BAT0/info Show state of cells in laptop battery# dmidecode -q | less Display SMBIOS/DMI information# smartctl -A /dev/sda | grep Power_On_Hours How long has this disk (system) been powered on in total# hdparm -i /dev/sda Show info about disk sda# hdparm -tT /dev/sda Do a read speed test on disk sda

Page 14: 20628549 Linux Commands

# badblocks -s /dev/sda Test for unreadable blocks on disk sdainteractive (see also linux keyboard shortcuts)• readline Line editor used by bash, python, bc, gnuplot, ...• screen Virtual terminals with detach capability, ...

• mcPowerful file manager that can browse rpm, tar, ftp, ssh, ...

• gnuplot Interactive/scriptable graphing• links Web browser• xdg-open http://www.pixelbeat.org/ open a file or url with the registered desktop applicationmiscellaneous

• alias hd='od -Ax -tx1z -v'Handy hexdump. (usage e.g.: • hd /proc/self/cmdline | less)

• alias realpath='readlink -f' Canonicalize path. (usage e.g.: • realpath ~/../$USER)• set | grep $USER Search current environment touch -c -t 0304050607 file Set file timestamp (YYMMDDhhmm)• python -m SimpleHTTPServer Serve current directory tree at http://$HOSTNAME:8000/

passwd Changes passwordnslookup Queries Internet domain name serversquota Displays disk usage and limitsmotd Message of the Dayfinger username User information lookup programman or xman command Displays pages of online manualxman Displays System Manual in Xless filename or more filename

Displays the contents of a file in the terminal one page at a time

infoDisplays information and documentation on shells, utilities and programs

clear Clears the terminal windowls directory List contents of a directorycat filename Displays the contents of a file in the terminalrm filename Removes a filepico filename or emacs filename

Opens and edits text files

cp sourcefile detstinationfilename

Copies a file

lpr filename Sends file to printergrep string filename looks through files for stringshead filename Displays first 10 lines of file

Page 15: 20628549 Linux Commands

tail filename Displays last 10 lines of filemv existingfilename newfilename

Moves or renames file

lpq filename Displays files in printing queuelprm filename Removes file from printing queuesort filename Displays and sorts file contentsdiff filename1 filename2 Displays differences between filesfile filename Displays information about file contentsecho string Copies string to terminaldate Displays current date and timecal Displays calendargzip filename Compresses a filecompress filename Compresses a filegunzip filename Decompresses a compressed filezcat filename Displays contents of a compressed fileapropos command Lists all man page titles/headers that contain the commandlynx Text based web browserdmesg Displays kernel ring bufferwhich command Displays path to commandwhereis command Displays paths to locations of commandswho Lists currently logged on users

finger username@hostnameObtains detailed information about a user currently using the system

w Lists currently logged on users with processing usagemesg y/n Sets options for letting other users write you messageswrite user Sends message to other userstalk user Allows two way chat to other userschmod permissions filename Changes file access permissionsmkdir directoryname Makes a directoryrmdir directoryname Removes an empty directoryln existingfile new-link Creates link to an existing file (hard link)stat filename Lists information about a fileln -s existingfile new-link Creates link to an existing file (soft link)df Displays all mounted filesystemsps Reports process status

command &

Sends a job to the background (job: one or more commands connected by a pipe "|" or pipes) The operating system assigns a number to the job when you press return. example: [1] 3578

top Displays updating list of currently running processes

Page 16: 20628549 Linux Commands

ttyDisplays the name of the terminal in which the command was issued

command > filename Redirects standard output command < filename Redirects standard inputcat file1 >> file2 Appends standard output from file1 to file2cat /dev/null > filename or filename > /dev/null

Redirects "bit bucket" or null string to file (only superuser has write access to this file)

command1 | command2Pipe sends standard output of one command to the standard input of another command

tr string1 string2 < inputfiletranslates each character in string1 to the corresponding character in string2

command | tee filename | grep string

Sends the output of one command to standard output and a file

bg %job number Sends job to the background by job numberfg %job number Brings job to the foreground by job number

kill PID or %job numberAborts a process by PID (Process Identification Number) or job number

jobs Displays a list of current jobsnetcfg Utility to set up PPP and network configurationsxev Utility used to see information flow from X server to client

echo $DISPLAYEnvironment variable that displays the ID string for a window

echo $PATH Variable that displays executable pathnetstat Displays network connectionsviewres Graphical class browser for X

xbillGame featuring Bill Gates trying to put windows on Macs and NeXT workstations

xevil Game similar to Loderunner?xchomp Linux's version of PacManxcmap Strange color lookup utilityxedit Text editor for Xasclock Clock from AfterStepxconsole Strange console for Xxmessage message Sends message to a dialog boxxgal XGalaga gamexg3 Image viewing programxgc Graphing calculator?xjewel Jewel game for Linuxxkbvleds LEDs?xkbwatch LEDs?

Page 17: 20628549 Linux Commands

xlogo Displays X logoxmixer Opens system sound controlsxsnow Snowflakes are fallin' on your desktopxwininfo Displays info about a windowstartx Starts an X Window System serverghostview Starts a text preview applicationxv filename Image viewerxsetroot -color Set background color in Xxcalc Starts a calculator in Xxclipboard Starts a clipboard in Xtraceroute host Prints the route packets take to the hosthostname Displays system identity namerlogin host Utility to connect to a remote system

telnet hostUtility to connect to a remote system (similar to rlogin but more interactive)

rcp file remotemachine Used to copy from a remote computerftp Utility to transfer files between systems on a network

rsh commandUtility to run a command on a remote system without logging in

ping host Utility used to test connection to a remote system

lcd directorypathChanges local machine directory while logged on to remote machine

Shared DirectoriesDirectory Description

/Root - The root directory is present in all Linux system file structures. It's the parent of all files in the system.

/binEssential common binaries - Holds files needed to boot the system and run it when it comes up in single user mode.

/boot Static files of the boot loader./dev Device files - All files that represent peripheral devices.

/etcMachine-local system configuration - Holds administrative, config, and other system files. Holds /etc/passwd file that contains a list of all users who have permission to the system.

/home User home directories - Contains each user's or client's home directory/lib Shared libraries/mnt Mount point for temporary partitions/proc Kernel and process information (virtual filesystem)/root Home directory for root/sbin Essential system binaries - Contains utilities for system administration./tmp Temporary files

Page 18: 20628549 Linux Commands

/usrSecond major hierarchy - Includes subdirectories that contain information used by the system.

/var Variable data - Contains files whose contents change as system runs.

vi CommandsCommand Description

vi filename Starts vi and creates a new file:q! Quits vi without saving workp Pastes data in buffer below current lineP Pastes data in buffer above current lineyy Copies current line:r !command Reads in output of the commandi Puts vi in insert mode:set autoindent Sets vi to indent automatically:set showmatch Sets vi to show matching parenthesis:set nu Sets vi to display line numbers:set showmode Sets vi to display the mode you're inESCAPE Sets vi to command modeControl-U Erases current line (insert mode)Control-H Erases on letter (insert mode)Control-W Erases current word (insert mode)h, j, k, l Moves cursor left, up, down, right respectivelyu Undoes last actionx Deletes a single characterdw Deletes a single worddd Deletes a single lineZZ Writes work buffer to disk and exits vio inserts line after cursor positionControl-L Redraws screen:w filename Save work as filename and exits

Control CharactersKey Use

Control-H or BACKSPACE Erases a character on the command lineControl-U Deletes an entire command lineControl-W Erases a word on the command lineControl-C Aborts program executionCOMMAND-Tab Switches ProgramsControl-L or CONtrOL-R Refreshes the screenControl-D, logout or exit Logs you off the system

Page 19: 20628549 Linux Commands

/etc/crontab The syntax of each line in this file is:

minute, hour, day of month, Month, day of week, (user name), command

/etc/fstab Columns are: device file to mount, directory to mount on, filesystem type, options, backup frequency, and fsck pass number (To specify the order in which filesystems should be checked on boot; 0 means no check.) The noauto option stops this mount from being done automatically on boot. Below is a detailed list of what is on each column.

1. The name of the device such as "/dev/hda1" 2. The mount point. Use "/" for root. Other typical mount points

are "/dos" for DOS, "swap" or "none" for the swap partition, and "/mnt/floppy" for "/dev/fd0" (the floppy drive).

3. The type of filesystem. They are: mini, ext, ext2(linux native), xiafs, msdos, hpfs, ntfs, fat32, iso9660(CD-ROM), NFS, swap (for swap space).

4. The mount options for use with the filesystem. Each filesystem type has different mount options. Read the mount man page to see possible options. ro= read only, user- allows normal users to mount the device.

5. The frequency the filesystem needs to be dumped (backed up) by the dump command. For ext2, normally make it 1, for others make it 0. 0 or nothing means it is not dumped. If 1, it is backed up during a system backup.

Page 20: 20628549 Linux Commands

6. A number telling the order in which the filesystems should be checked at reboot time by the fsck program. Your root should be 1, others are in ascending order or 0 to not be checked.

/etc/hosts Sets up host address information for local use. The format is:

IPaddress name1 name2...

/etc/inetd.conf Sets the services under the inetd daemon. The fields of this file are:

1. service name 2. socket type 3. protocol 4. wait or nowait 5. user 6. server program name

7. server program command line arguments /etc/inittab

Sets the init configuration. An entry in the inittab file has the following format:

id:runlevels:action:process

/etc/lilo.conf Tells LILO how to bootThe lilo.conf file below is for a system which has a Linux root partition on /dev/hda1 and a MS-DOS partition on /dev/hda2. See the "How Linux Works" guide and the "Linux User's Guidel" for more information.

boot = /dev/hda# Tell LILO to install the boot loader on the /dev/hda disk boot record

vga = normal # Set a normal video mode

delay = 60# The time in tenths of seconds to press <SHIFT> to get the LILO prompt# Equivalent would be "prompt" on one line, and "timeout=60" on# another line.

default=msdos# Sets the default boot to DOS, Without this line, the default is the first stanza

install = /boot/boot.b # The file containing the boot sector to usecompact # Have LILO perform some optimization.map = /boot/map #Specifies the map file LILO creates when installed

Page 21: 20628549 Linux Commands

# Section for Linux root partition on /dev/hda2.image = /vmlinuz # Location of kernellabel = linux # Name of the OS that is displayed in the LILO boot menu

root = /dev/hda1 # Location of root partition, if this isn't here the kernel image must have# this set using the rdev command

read-only # Mount read only on startup, Can also be set by rdev# Section for MSDOS partition on /dev/hda1.

other = /dev/hda2 # Location of partitiontable = /dev/hda # Location of partition table for /dev/hda2label = msdos # Name of OS (for boot menu)

if the command "vga= ask" is given, LILO will prompt the user for a video mode at boot time.

/etc/passwd The file has one line per username, and is divided into seven colon-delimited fields:

1. Username. 2. Password, in an encrypted form. 3. Numeric user id. 4. Numeric group id. 5. Full name or other description of account. This is called gecos. 6. The user's home directory. 7. The user's login shell (program to run at login).

The format is explained in more detail on the passwd manual page.

/usr/X11R6/lib/X11/XF86Config The main XFree86 configuration file. Type "man XF86Config"

• The first section is "Files" RgbPath Sets the path to the X11R6 RGB color databaseFontPath Sets the path to a directory containing X11 fonts

• The second section is "ServerFlags", all lines are commented out • The third section is "Keyboard" • The fourth section is "Pointer"

Protocol Specifies the mouse protocolDevice Specifies the device file by which the mouse can be accessed.

• The fifth section is "Monitor" which specifies the characteristics of your monitor ModeLine Specifies resolution modes for your monitor

• The file, VideoModes.doc describes in detail how to determine the ModeLine values for each resolution mode. Two files, modeDB.txt and Monitors,may have

Page 22: 20628549 Linux Commands

ModeLine information for your monitor. They are located in /usr/X11R6/lib/X11/doc.

• The sixth section is "Screen" describing the video/monitor card configuration for the particular server.The Driver line specifies the X server that you will be using. Valid Driver values are:

_ Accel: For the XF86 S3, XF86 Mach32, XF86 Mach8, XF86 8514,

XF86 P9000, XF86 AGX,and XF86 W32 servers;_ SVGA: For the XF86 SVGA server;_ VGA16: For the XF86 VGA16 server;_ VGA2: For the XF86 Mono server;_ Mono: For the non-VGA monochrome drivers in the XF86 Mono and XF86 VGA16 servers.Be sure that /usr/X11R6/bin/X is a symbolic link to this server.The Device line specifies the Identifier of the Device section that corresponds to the video card to use for this server. Above, we created a Device section with the line Identifier "#9 GXE 64"Therefore, we use "#9 GXE 64" on the Device line here. Similarly, the Monitor line specifies the name of the Monitor section to be used with this server. Here, "CTX 5468 NI" is the Identifier used in the Monitor section described above.

• Subsection "Display" defines several properties of the XFree86 server corre-sponding to your monitor/video card combination. The XF86Config file describes all of these options in detail. Most of them are not necessary to get the system working.The options that you should know about are:

o _ Depth. Defines the number of color planes; that is, the number of bits per pixel. Usually, Depth is set to 16. For the VGA16 server, you would use a depth of 4, and for the monochrome server a depth of 1. If you use an accelerated video card with enough memory to support more bits per pixel, you can set Depth to 24, or 32.

o _ Modes. This is the list of mode names that have been defined using the ModeLine directive(s) in the Monitor section. In the above section, we used ModeLines named "1024x768", "800x600",and "640x48"0. Therefore, we use a Modes line of

Modes "1024x768" "800x600" "640x480"

The first mode listed on this line is the default when XFree86 starts. After XFree86 is running, you can switch between the modes listed here using the keys Ctrl - Alt –Numeric + and Ctrl - Alt - Numeric - .It might be best, when you initially configure XFree86, to use lower resolution video modes like 640x480, which tend to work with most

Page 23: 20628549 Linux Commands

systems. Once you have the basic configuration working, you can modify XF86Config to support higher resolutions.

o _ Virtual. Set the virtual desktop size. XFree86 can use additional memory on your video card to extend the size of the desktop. When you move the mouse pointer to the edge of the display, the desktop scrolls, bringing the additional space into view. Even if you run the server at a lower video resolution like 800x600, you can set Virtual to the total resolution that your video card can support. A 1-megabyte video card can support 1024x768 at a depth of 8 bits per pixel; a 2-megabyte card 1280x1024 at depth 8, or 1024x768 at depth 16. Of course, the entire area will not be visible at once, but it can still be used. The Virtual feature is rather limited. If you want to use a true virtual desktop, fvwm and similar window managers allow you to have large, virtual desktops by hiding windows and using other techniques, instead of storing the entire desktop in video memory. See the manual pages for fvwm for more details about this. Some Linux systems use fvwm by default.

o _ ViewPort. If you are using the Virtual option that is described above, ViewPort sets the coordinates of the upper-left-hand corner of the virtual desktop when XFree86 starts up. Virtual 0 is often used. If this is unspecified, then the desktop is centered on the virtual desktop display, which may be undesirable to you.

badblocks Used to search a disk or partition for badblocks.cfdisk Similar to fdisk but with a nicer interface.debugfs Allows direct access to filesystems data structure.df Shows the disk free space on one or more filesystems.dosfsck Check and repair MS-Dos filesystems.du Shows how much disk space a directory and all its files contain.dump Used to back up an ext2 filesystem. Complement is restore.

dumpe2fsDump filesystem superblock and blocks group information. Ex: dumpe2fs /dev/hda2

e2fsck Check a Linux second extended filesystem.e2label Change the label on an ext2 filesystem.exportfs Used to set up filesystems to export for nfs (network file sharing).fdisk Used to fix or create partitions on a hard drive.fdformat Formats a floppy disk.

fsckUsed to add new blocks to a filesystem. Must not be run on a mounted file system.

hdparm Get/set hard disk geometry parameters, cylinders, heads, sectors.

Page 24: 20628549 Linux Commands

mkfsInitializes a Linux filesystem. This is a front end that runs a separate program depending on the filesystem's type.

mke2fs Create a Linux second extended filesystem.mkswap Sets up a Linux swap area on a device or file.mount Used to mount a filesystem. Complement is umount.

rdevQuery/set image root device, swap device, RAM disk size of video mode. What this does is code the device containing the root filesystem into the kernel image specified.

rdump Same as dump.rmt Remote magtape protocol module.restore Used to restore an ext2 filesystem.setfdprm Set floppy drive parameters.swapoff(8) Used to de-activate a swap partition.swapon(8) Used to activate a swap partition.sync Forces all unwritten blocks in the buffer cache to be written to disk.tune2fs Adjust tunable filesystem parameters on second extended filesystems.umount Unmounts a filesystem. Complement is mount.

aproposSearch the whatis database for files containing specific strings.

bdflushKernel daemon that saves dirty buffers in memory to the disk.

cdChange the current directory. With no arguments "cd" changes to the users home directory.

chmod

chmod <specification> <filename> - Effect: Change the file permissions.

Ex: chmod 751 myfileEffect: change the file permission to rwx for owner, re for group

Ex: chmod go=+r myfileEffect: Add read permission for the owner and the group

character meanings u-user, g-group, o-other, + add permission, - remove, r-read, w-write,x-exe

Ex: chmod a +rwx myfileEffect: Allow all users to read, write or execute myfile

Ex: chmod go -r myfileEffect: Remove read permission from the group and others

chmod +s myfile - Setuid bit on the file which allows the program to run with user or group privileges of the file.chmod {a,u,g,o}{+,-}{r,w,x} (filenames) - The syntax of the chmod command.

Page 25: 20628549 Linux Commands

chownchown <owner1> <filename> Effect: Change ownership of a file to owner1.

chgrp chgrp <group1> <filename> Effect: Change group.cksum Perform a checksum and count bytes in a file.

cp cp <source> <destination> Copy a file from one location to another.

ddConvert and copy a file formatting according to the options. Disk or data duplication.

dir List directory contents.dircolors Set colors up for ls.

fileDetermines file type. Also can tell type of library (a.out or ELF).

find

Ex: find $Home –name readme Print search for readme starting at home and output full path.How to find files quickly using the find command:Ex: find ~ -name report3 –print

• "~" = Search starting at the home directory and proceed through all its subdirectories

• "-name report3" = Search for a file named report3

• "-print" = Output the full path to that file install Copy multiple files and set attributes.ln Make links between files.locate File locating program that uses the slocate database.losetup Loopback device setup.

ls

List files. Option -a, lists all, see man page "man ls"Ex: "ls Docum Projects/Linux" - The contents of the directories Docum and Projects/Linux are listed.To list the contents of every subdirectory using the ls command:

1. Change to your home directory.

2. Type: ls -Rmkdir Make a directory.mknod Make a block or character special file.mktemp Make temporary filename.

mvMove or rename a file. Syntax: mv <source> <destination> Ex: mv filename directoryname/newfilename

pathchk Check whether filenames are valid or portable.

pwdPrint or list the working directory with full path (present working directory).

Page 26: 20628549 Linux Commands

rmEx: "rm .*" - Effect: Delete system files (Remove files) –i is interactive option.

rmdirrmdir <directory> - Remove a directory. The directory must be empty.

slocateProvides a secure way to index files and search for them. It builds a database of files on the system.

stat(1u) Used to print out inode information on a file.sum Checksum and count the blocks in a file.test Check file types and compare values.

touchChange file timestamps to the current time. Make the file if it doesn't exist.

update Kernel daemon to flush dirty buffers back to disk.vdir List directory contents.whatis Search the whatis database for complete words.

wherisLocate the binary, source and man page files for a command.

whichShow full path of commands where given commands reside.

File viewing and editing

ed Editoremacs Full screen editor.gitview A hexadecimal or ASC file viewer.head head linuxdoc.txt - Look at the first 10 lines of linuxdoc.txt.jed Editorjoe Editorless q-mandatory to exit, Used to view files.more b-back q-quit h-help, Used to view files.pico Simple text editor.tail tail linuxdoc.txt - Look at the last 10 lines of linuxdoc.txt.vi Editor with a command mode and text mode. Starts in command mode.

File compression, backing up and restoring

ar Create modify and extract from archives.bunzip2 Newer file decompression program.bzcat Decompress files to stdout.bzip2 Newer file compression program.bzip2recover Recovers data from damaged bzip2 files.compress Compress data.cpio Can store files on tapes. to/from archives.dump Reads the filesystem directly.

Page 27: 20628549 Linux Commands

gunzip unzip <file> - unzip a gz file.gzexe Compress executable files in place.gzip gzip <file> - zip a file to a gz file.mt Control magnetic tape drive operation.

tar

Can store files on tapes.Usage: tar cvf <destination> <files/directories> - Archive copy groups of filesEx: tar /dev/fdo temp Effect: Copy temp to drive A:

uncompress Expand data.

unzip unzip <file> - unzip a zip file. Files ending in ".gz" or ".zip" are compressed.

zcat Used to restore compressed files.zcmp Compare compressed files.zdiff Compare compressed files.zforce Force a .gz extension on all gzip files.zgrep Search possibly compressed files for a regular expression.zmore File filter for crt viewing of compressed text.znew Recompress .z files to .gz files.zip zip <file> - make a zip file.

Extra control and piping for files and other outputs

basename Strip directory and suffix information from filenames.

catEx: cat < filename --- Effect: put keyboard input into the file. CTRL-D to exit (end).

cmp Compare two files.colrm Remove columns from a file.column Columnate lists.

commEx: comm file1 file2 --- Effect compare the contents of file1 and file2 produces 3 columns of output. Lines in the first file, lines in second file, lines in both files.

csplit Split a file into sections determined by context lines.cut Remove sections from each line of files.diff Show the differences between files. Ex: diff file1 file2diff3 Find differences between 3 files.dirname Strip the non-directory suffix from a filename.echo Display a line of text.egrep Similar to grep -E, compatible with UNIX egrep.expand Convert tabs to spaces.expr Evaluate expressions.false Do nothing. Exit with a status indicating failure.fgrep Same as grep -F.fold Wrap each input line to fit in specified width.

Page 28: 20628549 Linux Commands

join Join lines of two files in a common field.

grep

grep pattern filename.Ex: grep " R " --- Effect: Search for R with a space on each sideEx: ls –a |grep R --- Effect: List all files with an R in them or their info listing.

hexdump asc, decimal, hex, octal dump.logname Print user's login name.look Display lines beginning with a given string.mkfifo Create named pipes with the given names.nl Write each file to standard output with line numbers added.od Dump files in octal and other formats.patch Apply a diff file to an original.paste Combines from 2 or more files. Ex: paste file1 file 2printf Print and format data.rev Reverses lines in a file.script Make a typescript of a terminal session.sdiff Find differences between 2 files and merge interactively.sed A stream editor. Used to perform transformations on an input stream.sleep Delay for a specified amount ot time.sort Sort a file alphabetically.split Split a file into pieces.strings Print the strings of printable characters in files.tac Concatenate and print files in reverse.tee Read from standard input and write to standard output and files.tr Translate or delete characters.true Do nothing. Exit with a status indicating success.tsort Perform topological sort.ul Do underlining.unexpand Convert tabs to spaces.uniq Remove duplicate lines from a sorted file.uudecode Used to transform files encoded by uuencode into their original form.

uuencodeEncode a binary file to be sent over a medium that doesn't support non-ASC data.

wc Count lines, words, characters in a file. Ex: wc filename.xargs Build and execute command lines from standard input.yes Output the string "y" until killed.

Page 29: 20628549 Linux Commands

aproposapropos keyword - Show all commands with the keyword in their description. The same as the "man -k" command.

helpBash shell help for the bash builtin command list. The help command gets help for a particular command.

man Get help from the manual for a command.

manman -k keyword - Show all commands with the keyword in their description"man 2 kill" - Display page 2 of the kill command

manpath Determine user's searchpath for manpages.

infoDocumentation on Linux commands and programs similar to the man pages but navigation is organized different.

Linux Job Management

at Similar to cron but run only once.

atqLists the user's pending jobs. If the user is the superuser, everybody's jobs are listed.

atrm Deletes at jobs.atrun Run jobs queued for later execution

batchExecutes commands when system load levels drop below 0.8 or value specified in atrun invocation.

cron

A deamon used to set commands to be run at specific times. Starts the commands in the crontab file. Used to clean up temporary files periodically in the /var/tmp and /tmp directories.

nice Run a program with modified scheduling priority.

nohupRun a command immune to hangups, with output to a non-tty.

watch Execute a program periodically showing output full screen.

Linux Process management

bg Starts a suspended process in the backgroundfg Starts a suspended process in the foregroundgitps A graphical process viewer and killer program.jobs Lists the jobs runningkill Ex: "kill 34" - Effect: Kill or stop the process with the process ID number 34.killall Kill processes by name. Can check for and restart processes.pidof Find the process ID of a running program ps Get the status of one or more processes. Options:

• u (more info)

Page 30: 20628549 Linux Commands

• a (see all) • -l (technical info)

Meanings:

• PPID-parent process ID • PID-process ID

ps ax |more to see all processes including daemonspstree Display the tree of running processes.

saGenerates a summary of information about users' processes that are stored in the /var/log/pacct file.

skill Report process status.snice Report process status.top Display the processes that are using the most CPU resources.CTRL-C Kills the current job.& At the end of the command makes it run in the background.

dnsdomainname Show the systems DNS domain namedomainname Show or set the systems domain name

hostnameUsed to show or set the name of your machine for networking

nisdomainname Show or set systems NIS/YP domain namenodename Show or set the systems DECnet node nameypdomainname Show or set the system's NIS/YP domain name

Network setup and commands

arpThis program lets the user read or modify their arp cache.

dig(1) Send domain name query packets to name servers for debugging or testing.

finger Display information about the system users.ftp File transfer program.ifconfig Configure a network interface.

Page 31: 20628549 Linux Commands

ifdown Shutdown a network interface.ifup Brings a network interface up. Ex: ifup eth0

ipchainsIP firewall administration used to set input, forward, and output rules.

netconfA GUI interactive program to let you configure a network on Redhat systems.

netconfigAnother GUI step by step network configuration program.

netstat

Displays information about the systems network connections, including port connections, routing tables, and more. The command "netstar -r" will display the routing table.

nslookupUsed to query DNS servers for information about hosts.

pftp Same as ftp.

pingSend ICMP ECHO_REQUEST packets to network hosts.

portmapDARPA port to RPC program number mapper. Must be running to make RPC calls.

rarp Manipulate the system's RARP table.

rcpRemote file copy. Copies files between two machines.

rexecRemote execution client for an exec server. The host uses the rexecd server.

ripqueryQuery RIP gateways. Request all routes known by an RIP gateway by sending an RIP request.

rlogin Starts a terminal session on a remote host.route Show or manipulate the IP routing table.rsh Executes command on remote host.

rupDisplays summary of current system status of a remote host or all hosts on the network.

ruptime Show host status of local machines.

rwhodSystem status server, maintains database used by rwho and ruptime.

showmount Show mount information for an NFS server.

tcpd

Access control facility for internet services. Can be set up to monitor requests for Telnet, finger, ftp, exec, rsh, rlogin, tftp, talk, comsat. It filters access for these requests.

tcpdchk Tcp wrapper configuration checker.

tcpdumpDump traffic on a network. Prints out headers of packets that match the boolean expression.

tcpdmatchPredicts how the tcp wrapper will handle a specific request for a service.

Page 32: 20628549 Linux Commands

TelnetUser interface to the TELNET protocol, setting up a remote console session.

traceroutePrint the route that packets take to the specified network host.

ipx_configure Tool to setup Netware access.ncpmount Netware filesystem mounting program.nprint Novell print command.pqlist Netware printer list for a given server.pserver Netware print server.slist Netware server list.

Communications commands (includes mail)

biff Notifies the system if mail arrives and who it is from.comsat Biff server to receive reports of incoming mail.expire Used to purge old news articles.elm Electronic mail.ftp File transfer protocol.mailx Berkley mail program.metasend Interface for sending non-text mail.nn Net news.

pineProgram for internet news and e-mail, Can send documents, graphics, local & remote messages.

sendmail A popular Unix, Linux mail message transfer agent.smail A popular mail message transfer agent which is easier to set up than sendmail.talk Lets two parties talk simultaneously.telnet Allows a user to have a login session across a network on a remote host.tin Net news reader.

writeAllows users to directly interact with other users via terminal number (one way at a time).

Environment

env Show all environment variables.

exportSet the value of a variable so it is visible to all subprocesses that belong to the current shell.

printenv Print all or part of environment.

Page 33: 20628549 Linux Commands

reset Restores runtime parameters for session to default values.

setShows how the environment is set up. This is a builtin bash command.

Library management

ldconfig Updates the necessary links for the run time link bindings.ldd Tells what libraries a given program needs to run.ltrace A library call tracer.trace Same as ltrace.

Module and kernel management

depmodHandle loadable modules automatically. Creates a makefile-like dependency file.

dmesgPrint or control the kernel ring buffer. This shows the last kernel startup messages.

genksyms Generate symbol version information.insmod Install loadable kernel module.lsmod List currently installed kernel modules.

modprobeUsed to load a set of modules that are marked with a specified tag.

rmmod Unload loadable modules.

Runtime level management

exit Terminates the shell.halt Stop the system.init Process control initialization.initscript Script that executes inittab commands.logout Log the user off the system.poweroff Brings the system down.reboot Reboot the system.runlevel List the current and previous runlevel.setsid Run a program in a new session.

shutdown

If your system has many users, use the command "shutdown -h +time message", where time is the time in minutes until the system is halted, and message is a short explanation of why the system is shutting down.# shutdown -h +10 'We will install a new disk. System should be back on-line in three hours.'

telinit By requesting run level 1 a system can be taken to single user mode.

System Configuration tools

Page 34: 20628549 Linux Commands

ctrlaltdel Set the function of the ctrl alt del combination.isapnp Configure ISA plug and play devices.

kbdconf A Redhat Linux tool which configures the /etc/sysconfig/keyboard file which specifies the location of the keyboard map file. This is a GUI based tool.

kbdrate Set the keyboard repeat rate and delay time.

kernelcfgA Redhat GUI kernel configuration tool, Start X, then run it from a console session.

linuxconf Redhat's GUI linux system configuration tool.lspci List all pci devices.mesg Control write access to your terminal.

mouseconfigA Redhat Linux tool used to configure the /etc/sysconfig.mouse file. This is a GUI tool.

ndc Script file used to restart, stop, start the DNS server.Printtool Redhat's GUI printer configuration tool.quota Display disk usage and limits.quotacheck Scan a filesystem for disk usages.quotaoff Turn file system quotas off.quotaon Turn file system quotas on.

sambaScript file used to stop, start, restart samba services when not run using inetd.

setpci Configure pci devices.setserial Set/get serial port information.setterm Set terminal attributes.setup Set up devices and file systems.stty Used to configure and print the console devices.swapon Enable devices and files for paging and swapping.swapoff Disable devices and files for paging and swapping.

timeconfigA Redhat Linux tool used to configure the /etc/sysconfig/clock file. This is a GUI tool used to set timezone and whether or not the clock is set to GMT time.

tset Used to initialize terminals.

System Information

arch Print machine architecture.df Shows disk free space.du Shows disk usage.free Display used and free memory on the system.ipcrm Provide information on ipc facilities.ipcs Same as ipcrm.lsdev Display information about installed hardware via files in the /proc directory.lsof List open files.

Page 35: 20628549 Linux Commands

lspci List PCI devices .pnpdump Lists ISA plug and play devices resource information.procinfo Display system status gathered from proc.pstree Display a tree of processes.runlevel Find the current and previous system runlevel.strace Trace ssytem calls and signals for a binary program.stty Change and print terminal line settings.tload Prints a graphic representation of the system load average.tty Print the filename of the terminal connected to standard input.uname Print system information, Prints Linux.vmstat Report virtual memory statistics.xcpustate Displays CPU states (idle, nice, system, kernel) statistics. Runs in X?

System Logging

klogd Kernel log daemon which intercepts and logs Linux kernel messages.logger Make entries in the system log.syslogd Linux system logging utilities.sysklogd Linux system logging utilities.

System Security

System time

cal Calendar.

clockUsed to change or get current time. The command "clock -–w" sets the hardware clock.

date Print or set the system date and time.hwclock Set or read the hardware CMOS clock.

timedTime server daemon to synchronize the host's time with other machines, normally invoked at boot time from the rc(8) file.

timedc Timed control program.

tzsetUsed to change the users private time zone by setting the TZ environment variable.

uptime Reports how long the system has been running.zdump Prints the current time in each zonename named on the command line.

zicReads text from files named on the command line and creates time conversion files.

X Management and programs

SuperProbe Probe video hardware.Xconfigurator The Redhat tool used during system setup to configure X.

Page 36: 20628549 Linux Commands

xconsole Displays messages usually sent to /dev/console.xf86config Older version of XF86Setup.

XF86SetupA newer X configuration program with a GUI interface which modifies the "/etc/X11/XF86Config" configuration file.

xvidtuneThis program will test video modes on the fly without modification to your X configuration. Read the usr/X11R6/lib/X11/doc/VideoModes.doc file before running this program.

Linux User Managementac Print statistics about users' connect time.accton Turn on accounting of processes. To turn it on type "accton /var/log/pacct".adduser Ex: adduser mark - Effect: Adds a user to the system named markchage Used to change the time the user's password will expire.chfn Change the user full name field finger informationchgrp Changes the group ownership of files.chown Change the owner of file(s ) to another user.chpasswd Update password file in batch.chroot Run command or interactive shell with special root directory.chsh Change the login shell.

edquota

Used to edit user or group quotas. This program uses the vi editor to edit the quota.user and quota.group files. If the environment variable EDITOR is set to emacs, the emacs editor will be used. Type "export EDITOR=emacs" to set that variable.

faillog Examine faillog and set login failure limits.finger See what users are running on a system.gpasswd Administer the /etc/group file.groupadd Create a new group.grpck Verify the integrity of group files.

grpconvCreates /etc/gshadow from the file /etc/group which converts to shadow passwords.

grpunconvUses the files /etc/passwd and /etc/shadow to create /etc/passwd, then deletes /etc/shadow which converts from shadow passwords.

groupdel Delete a group.groupmod Modify a group.groups Print the groups a user is inid Print real and effective user id and group ids.last Display the last users logged on and how long.

Page 37: 20628549 Linux Commands

lastbShows failed login attempts. This command requires the file /var/log/btmp to exist in order to work. Type "touch /var/log/btmp" to begin logging to this file.

lastcommDisplay information about previous commands in reverse order. Works only if process accounting is on.

lastlog Formats and prints the contents of the last login.logname Print user's login name.newgrp Lets a suer log in to a new group.newusers Update and create newusers in batch.passwd Set a user's pass word.pwck Verify integrity of password files.pwconv Convert to and from shadow passwords and groups.quota Display users' limits and current disk usage.quotaoff Turns system quotas off.quotaon Turns system quotas on.quotacheck Used to check a filesystem for usage, and update the quota.user file.repquota Lists a summary of quota information on filesystems.

saGenerates a summary of information about users' processes that are stored in the /var/log/pacct file.

smbclientWorks similar to an ftp client enabling the user to transfer files to and from a windows based computer.

smbmountAllows a shared directory on a windows machine to be mounted on the Linux machine.

smbpasswd Program to change users passwords for samba.

suEx: su mark - Effect: changes the user to mark, If not root will need marks password.

sulogin Single user login.ulimit A bash builtin command for setting the processes a user can run.useradd Create a new user or update default new user information.userdel Delete a user account and related files.usermod Modify a user account.users Print the user names of users currently logged in.utmpdump Used for debugging.vigr Edit the password or group files.vipw Edit the password or group files.w Display users logged in and what they are doing.wall Send a message to everybody's terminal.who Display the users logged in.whoami Print effective user id.

Page 38: 20628549 Linux Commands

Linux Printing and Programming

Linux Printing

banner Print a large banner on printer.

lprPrint, submits a job to the printer.Ex: lpr -Pdest filename. Dest is the destination printer. the name of the file to print is filename.

lpc Lets you check the status of the printer and set its state.lpq Shows the contents of a spool directory for a given printer.lprm Removes a job from the printer queue.gs Ghostscript - A PostScript interpreter.pr Print a file. Ex: pr filename |pg.tunelp Set various parameters for the lp device.

Linux Programming

as86 Assemblerawk C programming language - allows finding of lines with specific characters.bc A precision calculator language.cproto Reads in c source files and generates function prototypes for all the functions.ctags Generate tag (index) files for source code.dialog Display dialog boxes from shell scripts.egcs GNU project C and C++ compiler.f2c Converts fortran code to c code.gawk Pattern scanning and processing language. GNU's implementation of awk.

gcc

GNU c and c++ compiler. -g Produce debugging information.

-pgGenerate profile info that will allow the gprof program to display timing info.

gdb Debugging program.

gprofIn /usr/bin, allows you to tell where most of the execution time is spent in a program.

igawk Gawk with include files.

indentReformats c source code for consistent indenting and opening and closing brackets consistent.

ld The GNU linker.ld86 Linker for as86.make GNU make utility to maintain a group of programs.nm Lists symbols from object files.objcopy Copy and translate object files.objdump Display information from object files.

Page 39: 20628549 Linux Commands

p2c Converts pascal code to c code.

prompt

set prompt = "waldo" (in C shell) ps1 = 'waldo' (in BOURNE shell)PS1="[\u@\h \w]\\$ " makes prompt = [username@hostname current directory]see the BASH or your shell's man page for more information.

size List section sizes and total size.strip Discard symbols from object files.xxgdb X windows based graphical user interface to gdb.

Scripting Languages

Perl A command interpreter for the Practical Extraction and Report Language (perl).Python A report language.Tcl Tool command language shell. Enter by typing tclsh.info Return information about the state of the Tcl interpreter.

TkA graphical user extension to Tcl based on X windows. Commands are same as Tcl.

Linux Document Preparationaddftinfo Add information to troff font files for use with groff.afmtodit Create font files for use with groff.colcrt Filter nroff output for CRT previewing.enscript Convert text files to postscript.

eqnFormat equations for troff. Compiles descriptions of equations embedded in troff.

geqn Used to print special symbols and complex equations. Not user friendly.git GNU interactive tools.gitaction Per file type action script.gitkeys Display key sequence utility.gitmount Allows any block device to be mounted.gitps A graphical process viewer and killer program.gitrgrep A recursive grep program.gitunpack Used to unpack archive files in a given directory.gitview A hexadecimal or ASC file viewer.grodvi Convert Groff output to TeX dvi format, normally run by groff.groff Used as a front end for the groff document formatting system.

Page 40: 20628549 Linux Commands

grops Postscript driver for groff. invoked by groff.gtbl Used to prepare charts, multicolumn lists and tabular formats.hpftodit Create font description files for use with groff.indxbib Make inverted index for bibliographic databases.lookbib Search bibliographic databases.nroff Emulate nroff command with groff.pfbtops Translate a postscript font in .pbf format to ASCII.pic Compile pictures for troff or Tex.psbb Extract bounding box from postscript document.refer Preprocess bibliographic references for groff.rpm2html Make an html database from rpm repository.soelim Interpret .so requests in groff input.tbl Format tables for groff.

TeXUsed to format professionally typeset documents (Chapters, Headings, and paragraphs).

texi2html Texinfo to html converter.tfmtodit Create font files for use with groff.troff Formats documents as part of the groff document formatting system.yacc A parser generator.

Page 41: 20628549 Linux Commands

Miscellaneous Linux Commands

Keys and keycodes and console

dumpkeys Dump keyboard translation tables.getkeycodes Print kernel scancode-to-keycode mapping table.lesskey Specify key bindings for less.loadkeys Load keyboard translation tables.psfaddtable Add a unicode character table to a console font.

psfgettableExtract the embedded Unicode character table from a console font.

psfstriptableRemove the embedded Unicode character table from a console font.

resizecons Change kernel idea of the console size.setkeycodes Load kernel scancode-to-keycode mapping table.

Ncurses functions

captoinfo Convert a termcap description into a terminfo description.clear Clear the terminal screen.infocmp Compare or print out terminfo descriptions.reset Restore run-time parameters for session to default values.tie Merge or apply WEB change files.toe Table of terminfo entries.tput Initialize a terminal or query terminfo database.tset Terminal initialization.

CD programs

cdparanoia An audio CD reading utility.cdrecord Record audio or data compact Disks from a master.

Other

aliasEx:: alias dir='ls -a' - Effect: Makes dir list all files (no spaces next to the = sign).

bison GNU project parser generator.chvt Change foreground virtual terminal.crack Program used to find bad passwords or crack security.cvs Concurrent Versions System.deallocvt Gets rid of unused virtual terminals.dumpkeys Dump keyboard translation tables.

Page 42: 20628549 Linux Commands

fc Fix command. Used to edit the commands in the current history list.

gdbm The GNU database manager.gpm A cut and paste mouse server.history Show commands listed in the shell history (last n).lilo Boot management program.mc Visual shell for Unix like system. A file manager.nc A file manager.pdksh Public domain Korn shell.pilot Filesystem browser.PS1="Please enter a command" Set Bash level 1 response.PS2="I need more information" Set Bash level 2 response.rcs Recision Control system. Change RCS file attributes.sash Standalone shell with built in commands.screen Screen manager with VT100 terminal emulation.sleep Ex: "sleep 2" - wait 2 seconds.

tcshC shell with filename completion and command line editing.

unalias Ex: "unalias dir" - Effect: Removes the alias dir.units Unit conversion program.

variables

• set - Ex: set t=/temp • unset - Ex: unset t

• echo - Ex: echo $t zsh The Z shell.

ttysnoopA program that comes with some systems that lets the administrator to snoop on the user's terminals.