You are on page 1of 75

Unix LS Command: 15 Practical Examples

ls Unix users and sysadmins cannot live without this two letter command. Whether you use it 10 times a day or 100 times a day, knowing the power of ls command can make your command line journey enjoyable. In this article, let us review 15 practical examples of the mighty ls command. 1. Open Last Edited File Using ls -t To open the last edited file in the current directory use the combination of ls, head and vi commands as shown below. ls -t sorts the file by modification time, showing the last edited file first. head -1 picks up this first file.
$ vi first-long-file.txt $ vi second-long-file.txt $ vi `ls -t | head -1` [Note: This will open the last file you edited (i.e second-longfile.txt)]

2. Display One File Per Line Using ls -1 To show single entry per line, use -1 option as shown below.
$ ls -1 bin boot cdrom dev etc home initrd initrd.img lib

3. Display All Information About Files/Directories Using ls -l


$ ls -l -rw-r----- 1 ramesh team-dev 9275204 Jun 13 15:27 mthesaur.txt.gz

1st Character File Type: First character specifies the type of the file. In the example above the hyphen (-) in the 1st character indicates that this is a normal file. Following are the possible file type options in the 1st character of the ls -l output. o Field Explanation o - normal file o d directory o s socket file o l link file Field 1 File Permissions: Next 9 character specifies the files permission. Each 3 characters refers to the read, write, execute permissions for user, group and world In this example, -rw-r indicates read-write permission for user, read permission for group, and no permission for others. Field 2 Number of links: Second field specifies the number of links for that file. In this example, 1 indicates only one link to this file. Field 3 Owner: Third field specifies owner of the file. In this example, this file is owned by username ramesh. Field 4 Group: Fourth field specifies the group of the file. In this example, this file belongs to team-dev group. Field 5 Size: Fifth field specifies the size of file. In this example, 9275204 indicates the file size. Field 6 Last modified date & time: Sixth field specifies the date and time of the last modification of the file. In this example, Jun 13 15:27 specifies the last modification time of the file. Field 7 File name: The last field is the name of the file. In this example, the file name is mthesaur.txt.gz.

4. Display File Size in Human Readable Format Using ls -lh Use ls -lh (h stands for human readable form), to display file size in easy to read format. i.e M for MB, K for KB, G for GB.
$ ls -l -rw-r----- 1 ramesh team-dev 9275204 Jun 12 15:27 arch-linux.txt.gz* $ ls -lh -rw-r----- 1 ramesh team-dev 8.9M Jun 12 15:27 arch-linux.txt.gz

5. Display Directory Information Using ls -ld When you use ls -l you will get the details of directories content. But if you want the details of directory then you can use -d option as., For example, if you use ls

-l /etc will display all the files under etc directory. But, if you want to display the information about the /etc/ directory, use -ld option as shown below.
$ ls -l /etc total 3344 -rw-r--r--rw-r--r-drwxr-xr-x -rw-r--r-drwxr-xr-x

1 1 4 1 4

root root root root root

root root root root root

15276 2562 4096 48 4096

Oct Oct Feb Feb Feb

5 5 2 8 2

2004 2004 2007 2008 2007

a2ps.cfg a2ps-site.cfg acpi adjtime alchemist

$ ls -ld /etc drwxr-xr-x 21 root root 4096 Jun 15 07:02 /etc

6. Order Files Based on Last Modified Time Using ls -lt To sort the file names displayed in the order of last modification time use the -t option. You will be finding it handy to use it in combination with -l option.
$ ls -lt total 76 drwxrwxrwt 14 root root 4096 Jun drwxr-xr-x 121 root root 4096 Jun drwxr-xr-x 13 root root 13780 Jun drwxr-xr-x 13 root root 4096 Jun drwxr-xr-x 12 root root 4096 Jun drwxr-xr-x 2 root root 4096 May lrwxrwxrwx 1 root root 11 May drwx-----2 root root 16384 May drwxr-xr-x 15 root root 4096 Jul

22 22 22 20 18 17 17 17 2

07:36 07:05 07:04 23:12 08:31 21:21 20:29 20:29 2008

tmp etc dev root home sbin cdrom -> media/cdrom lost+found var

7. Order Files Based on Last Modified Time (In Reverse Order) Using ls -ltr To sort the file names in the last modification time in reverse order. This will be showing the last edited file in the last line which will be handy when the listing goes beyond a page. This is my default ls usage. Anytime I do ls, I always use ls -ltr as I find this very convenient.
$ ls -ltr total 76 drwxr-xr-x drwx-----lrwxrwxrwx drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x 15 2 1 2 12 13 13 root root root root root root root root 4096 Jul 2 2008 var root 16384 May 17 20:29 lost+found root 11 May 17 20:29 cdrom -> media/cdrom root 4096 May 17 21:21 sbin root 4096 Jun 18 08:31 home root 4096 Jun 20 23:12 root root 13780 Jun 22 07:04 dev

drwxr-xr-x 121 root root drwxrwxrwt 14 root root

4096 Jun 22 07:05 etc 4096 Jun 22 07:36 tmp

8. Display Hidden Files Using ls -a (or) ls -A To show all the hidden files in the directory, use -a option. Hidden files in Unix starts with . in its file name.
$ ls -a [rnatarajan@asp-dev ~]$ ls -a . Debian-Info.txt .. CentOS-Info.txt .bash_history Fedora-Info.txt .bash_logout .lftp .bash_profile libiconv-1.11.tar.tar .bashrc libssh2-0.12-1.2.el4.rf.i386.rpm

It will show all the files including the . (current directory) and .. (parent directory). To show the hidden files, but not the . (current directory) and .. (parent directory), use option -A.
$ ls -A Debian-Info.txt Fedora-Info.txt CentOS-Info.txt Red-Hat-Info.txt .bash_history SUSE-Info.txt .bash_logout .lftp .bash_profile libiconv-1.11.tar.tar .bashrc libssh2-0.12-1.2.el4.rf.i386.rpm [Note: . and .. are not displayed here]

9. Display Files Recursively Using ls -R


$ ls /etc/sysconfig/networking devices profiles $ ls -R /etc/sysconfig/networking /etc/sysconfig/networking: devices profiles /etc/sysconfig/networking/devices: /etc/sysconfig/networking/profiles: default /etc/sysconfig/networking/profiles/default:

To show all the files recursively, use -R option. When you do this from /, it shows all the unhidden files in the whole file system recursively.

10. Display File Inode Number Using ls -i Sometimes you may want to know the inone number of a file for internal maintenance. Use -i option as shown below to display inone number. Using inode number you can remove files that has special characters in its name as explained in the example#6 of the find command article.
$ ls -i /etc/xinetd.d/ 279694 chargen 279724 cups-lpd 279695 chargen-udp 279696 daytime 279697 daytime-udp 279698 echo

11. Hide Control Characters Using ls -q To print question mark instead of the non graphics control characters use the -q option.
ls -q

12. Display File UID and GID Using ls -n Lists the output like -l, but shows the uid and gid in numeric format instead of names.
$ ls -l ~/.bash_profile -rw-r--r-- 1 ramesh ramesh 909 Feb 8 11:48 /home/ramesh/.bash_profile $ ls -n ~/.bash_profile -rw-r--r-- 1 511 511 909 Feb 8 11:48 /home/ramesh/.bash_profile [Note: This display 511 for uid and 511 for gid]

13. Visual Classification of Files With Special Characters Using ls -F Instead of doing the ls -l and then the checking for the first character to determine the type of file. You can use -F which classifies the file with different special character for different kind of files.
$ ls -F Desktop/ Documents/ Templates/ Ubuntu-App@ firstfile Music/ Public/

Thus in the above output,


/ directory. nothing normal file.

@ link file. * Executable file

14. Visual Classification of Files With Colors Using ls -F Recognizing the file type by the color in which it gets displayed is an another kind in classification of file. In the above output directories get displayed in blue, soft links get displayed in green, and ordinary files gets displayed in default color.
$ ls --color=auto Desktop Documents Examples firstfile Music Templates Videos Pictures Public

15. Useful ls Command Aliases You can take some required ls options in the above, and make it as aliases. We suggest the following.

Long list the file with size in human understandable form.


alias ll="ls -lh"

Classify the file type by appending special characters.


alias lv="ls -F"

Classify the file type by both color and special character.


alias ls="ls -F --color=auto"

15 Examples To Master Linux Command Line History

When you are using Linux command line frequently, using the history effectively can be a major productivity boost. In fact, once you

have mastered the 15 examples that Ive provided here, youll find using command line more enjoyable and fun. 1. Display timestamp using HISTTIMEFORMAT Typically when you type history from command line, it displays the command# and the command. For auditing purpose, it may be beneficial to display the timepstamp along with the command as shown below.
# export HISTTIMEFORMAT='%F %T ' # history | more 1 2008-08-05 19:02:39 service network restart 2 2008-08-05 19:02:39 exit 3 2008-08-05 19:02:39 id 4 2008-08-05 19:02:39 cat /etc/redhat-release

2. Search the history using Control+R I strongly believe, this may be your most frequently used feature of history. When youve already executed a very long command, you can simply search history using a keyword and re-execute the same command without having to type it fully. Press Control+R and type the keyword. In the following example, I searched for red, which displayed the previous command cat /etc/redhat-release in the history that contained the word red.
# [Press Ctrl+R from the command prompt, which will display the reverse-i-search prompt] (reverse-i-search)`red': cat /etc/redhat-release [Note: Press enter when you see your command, which will execute the command from the history] # cat /etc/redhat-release Fedora release 9 (Sulphur)

Sometimes you want to edit a command from history before executing it. For e.g. you can search for httpd, which will display service httpd stop from the command history, select this command and change the stop to start and reexecute it again as shown below.
# [Press Ctrl+R from the command prompt, which will display the reverse-i-search prompt] (reverse-i-search)`httpd': service httpd stop [Note: Press either left arrow or right arrow key when you see your command, which will display the command for you to edit, before executing it] # service httpd start

3. Repeat previous command quickly using 4 different methods Sometime you may end up repeating the previous commands for various reasons. Following are the 4 different ways to repeat the last executed command.
1. 2. 3. 4.

Use the up arrow to view the previous command and press enter to execute it. Type !! and press enter from the command line Type !-1 and press enter from the command line. Press Control+P will display the previous command, press enter to execute it

4. Execute a specific command from history In the following example, If you want to repeat the command #4, you can do !4 as shown below.
# history | more 1 service network restart 2 exit 3 id 4 cat /etc/redhat-release # !4 cat /etc/redhat-release Fedora release 9 (Sulphur)

5. Execute previous command that starts with a specific word Type ! followed by the starting few letters of the command that you would like to re-execute. In the following example, typing !ps and enter, executed the previous command starting with ps, which is ps aux | grep yp.
# !ps ps aux | grep yp root 16947 0.0 ypbind root 17503 0.0 yp

0.1 0.0

36516 4124

1264 ? 740 pts/0

Sl S+

13:10 19:19

0:00 0:00 grep

6. Control the total number of lines in the history using HISTSIZE

Append the following two lines to the .bash_profile and relogin to the bash shell again to see the change. In this example, only 450 command will be stored in the bash history.
# vi ~/.bash_profile HISTSIZE=450 HISTFILESIZE=450

7. Change the history file name using HISTFILE By default, history is stored in ~/.bash_history file. Add the following line to the .bash_profile and relogin to the bash shell, to store the history command in .commandline_warrior file instead of .bash_history file. Im yet to figure out a practical use for this. I can see this getting used when you want to track commands executed from different terminals using different history file name.
# vi ~/.bash_profile HISTFILE=/root/.commandline_warrior

If you have a good reason to change the name of the history file, please share it with me, as Im interested in finding out how you are using this feature. 8. Eliminate the continuous repeated entry from history using HISTCONTROL In the following example pwd was typed three times, when you do history, you can see all the 3 continuous occurrences of it. To eliminate duplicates, set HISTCONTROL to ignoredups as shown below.
# pwd # pwd # pwd # history | tail -4 44 pwd 45 pwd 46 pwd [Note that there are three pwd commands in history, after executing pwd 3 times as shown above] 47 history | tail -4 # export HISTCONTROL=ignoredups # pwd # pwd # pwd # history | tail -3 56 export HISTCONTROL=ignoredups

57 pwd [Note that there is only one pwd command in the history, even after executing pwd 3 times as shown above] 58 history | tail -4

9. Erase duplicates across the whole history using HISTCONTROL The ignoredups shown above removes duplicates only if they are consecutive commands. To eliminate duplicates across the whole history, set the HISTCONTROL to erasedups as shown below.
# export HISTCONTROL=erasedups # pwd # service httpd stop # history | tail -3 38 pwd 39 service httpd stop 40 history | tail -3 # ls -ltr # service httpd stop # history | tail -6 35 export HISTCONTROL=erasedups 36 pwd 37 history | tail -3 38 ls -ltr 39 service httpd stop [Note that the previous service httpd stop after pwd got erased] 40 history | tail -6

10. Force history not to remember a particular command using HISTCONTROL When you execute a command, you can instruct history to ignore the command by setting HISTCONTROL to ignorespace AND typing a space in front of the command as shown below. I can see lot of junior sysadmins getting excited about this, as they can hide a command from the history. It is good to understand how ignorespace works. But, as a best practice, dont hide purposefully anything from history.
# export HISTCONTROL=ignorespace # ls -ltr # pwd # service httpd stop [Note that there is a space at the beginning of service, to ignore this command from history] # history | tail -3

67 68 69

ls -ltr pwd history | tail -3

11. Clear all the previous history using option -c Sometime you may want to clear all the previous history, but want to keep the history moving forward.
# history -c

12. Subtitute words from history commands When you are searching through history, you may want to execute a different command but use the same parameter from the command that youve just searched. In the example below, the !!:$ next to the vi command gets the argument from the previous command to the current command.
# ls anaconda-ks.cfg anaconda-ks.cfg # vi !!:$ vi anaconda-ks.cfg

In the example below, the !^ next to the vi command gets the first argument from the previous command (i.e cp command) to the current command (i.e vi command).
# cp anaconda-ks.cfg anaconda-ks.cfg.bak anaconda-ks.cfg # vi !^ vi anaconda-ks.cfg

13. Substitute a specific argument for a specific command. In the example below, !cp:2 searches for the previous command in history that starts with cp and takes the second argument of cp and substitutes it for the ls -l command as shown below.
# cp ~/longname.txt /really/a/very/long/path/long-filename.txt # ls -l !cp:2 ls -l /really/a/very/long/path/long-filename.txt

In the example below, !cp:$ searches for the previous command in history that starts with cp and takes the last argument (in this case, which is also the second

argument as shown above) of cp and substitutes it for the ls -l command as shown below.
# ls -l !cp:$ ls -l /really/a/very/long/path/long-filename.txt

14. Disable the usage of history using HISTSIZE If you want to disable history all together and dont want bash shell to remember the commands youve typed, set the HISTSIZE to 0 as shown below.
# export HISTSIZE=0 # history # [Note that history did not display anything]

15. Ignore specific commands from the history using HISTIGNORE Sometimes you may not want to clutter your history with basic commands such as pwd and ls. Use HISTIGNORE to specify all the commands that you want to ignore from the history. Please note that adding ls to the HISTIGNORE ignores only ls and not ls -l. So, you have to provide the exact command that you would like to ignore from the history.
# # # # # export HISTIGNORE="pwd:ls:ls -ltr:" pwd ls ls -ltr service httpd stop

# history | tail -3 79 export HISTIGNORE="pwd:ls:ls -ltr:" 80 service httpd stop 81 history [Note that history did not record pwd, ls and ls -ltr]

1. tar command examples Create a new tar archive.


$ tar cvf archive_name.tar dirname/

Extract from an existing tar archive.


$ tar xvf archive_name.tar

View an existing tar archive.


$ tar tvf archive_name.tar

More tar examples: The Ultimate Tar Command Tutorial with 10 Practical Examples 2. grep command examples Search for a given string in a file (case in-sensitive search).
$ grep -i "the" demo_file

Print the matched line, along with the 3 lines after it.
$ grep -A 3 -i "example" demo_text

Search for a given string in all files recursively


$ grep -r "ramesh" *

More grep examples: Get a Grip on the Grep! 15 Practical Grep Command Examples 3. find command examples Find files using file-name ( case in-sensitve find)
# find -iname "MyCProgram.c"

Execute commands on files found by the find command


$ find -iname "MyCProgram.c" -exec md5sum {} \;

Find all empty files in home directory


# find ~ -empty

More find examples: Mommy, I found it! 15 Practical Linux Find Command Examples 4. ssh command examples Login to remote host

ssh -l jsmith remotehost.example.com

Debug ssh client


ssh -v -l jsmith remotehost.example.com

Display ssh client version


$ ssh -V OpenSSH_3.9p1, OpenSSL 0.9.7a Feb 19 2003

More ssh examples: 5 Basic Linux SSH Client Commands 5. sed command examples When you copy a DOS file to Unix, you could find \r\n in the end of each line. This example converts the DOS file format to Unix file format using sed command.
$sed 's/.$//' filename

Print file content in reverse order


$ sed -n '1!G;h;$p' thegeekstuff.txt

Add line number for all non-empty-lines in a file


$ sed '/./=' thegeekstuff.txt | sed 'N; s/\n/ /'

More sed examples: Advanced Sed Substitution Examples 6. awk command examples Remove duplicate lines using awk
$ awk '!($0 in array) { array[$0]; print }' temp

Print all lines from /etc/passwd that has the same uid and gid
$awk -F ':' '$3==$4' passwd.txt

Print only specific field from a file.


$ awk '{print $2,$5;}' employee.txt

More awk examples: 8 Powerful Awk Built-in Variables FS, OFS, RS, ORS, NR, NF, FILENAME, FNR 7. vim command examples Go to the 143rd line of file
$ vim +143 filename.txt

Go to the first match of the specified


$ vim +/search-term filename.txt

Open the file in read only mode.


$ vim -R /etc/passwd

More vim examples: How To Record and Play in Vim Editor 8. diff command examples Ignore white space while comparing.
# diff -w name_list.txt name_list_new.txt 2c2,3 < John Doe --- > John M Doe > Jason Bourne

More diff examples: Top 4 File Difference Tools on UNIX / Linux Diff, Colordiff, Wdiff, Vimdiff 9. sort command examples Sort a file in ascending order
$ sort names.txt

Sort a file in descending order


$ sort -r names.txt

Sort passwd file by 3rd field.


$ sort -t: -k 3n /etc/passwd | more

10. export command examples To view oracle related environment variables.


$ export | declare -x declare -x declare -x declare -x grep ORACLE ORACLE_BASE="/u01/app/oracle" ORACLE_HOME="/u01/app/oracle/product/10.2.0" ORACLE_SID="med" ORACLE_TERM="xterm"

To export an environment variable:


$ export ORACLE_HOME=/u01/app/oracle/product/10.2.0

11. xargs command examples Copy all images to external hard-drive


# ls *.jpg | xargs -n1 -i cp {} /external-hard-drive/directory

Search all jpg images in the system and archive it.


# find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz

Download all the URLs mentioned in the url-list.txt file


# cat url-list.txt | xargs wget c

12. ls command examples Display filesize in human readable format (e.g. KB, MB etc.,)
$ ls -lh -rw-r----- 1 ramesh team-dev 8.9M Jun 12 15:27 arch-linux.txt.gz

Order Files Based on Last Modified Time (In Reverse Order) Using ls -ltr
$ ls -ltr

Visual Classification of Files With Special Characters Using ls -F


$ ls -F

More ls examples: Unix LS Command: 15 Practical Examples

13. pwd command pwd is Print working directory. What else can be said about the good old pwd who has been printing the current directory name for ages. 14. cd command examples Use cd - to toggle between the last two directories Use shopt -s cdspell to automatically correct mistyped directory names on cd More cd examples: 6 Awesome Linux cd command Hacks 15. gzip command examples To create a *.gz compressed file:
$ gzip test.txt

To uncompress a *.gz file:


$ gzip -d test.txt.gz

Display compression ratio of the compressed file using gzip -l


$ gzip -l *.gz compressed 23709 uncompressed 97975 ratio uncompressed_name 75.8% asp-patch-rpms.txt

16. bzip2 command examples To create a *.bz2 compressed file:


$ bzip2 test.txt

To uncompress a *.bz2 file:


bzip2 -d test.txt.bz2

More bzip2 examples: BZ is Eazy! bzip2, bzgrep, bzcmp, bzdiff, bzcat, bzless, bzmore examples 17. unzip command examples

To extract a *.zip compressed file:


$ unzip test.zip

View the contents of *.zip file (Without unzipping it):


$ unzip -l jasper.zip Archive: jasper.zip Length Date Time -------------40995 11-30-98 23:50 32169 08-25-98 21:07 15964 08-25-98 21:07 10542 08-25-98 21:07

Name ---META-INF/MANIFEST.MF classes_ classes_names classes_ncomp

18. shutdown command examples Shutdown the system and turn the power off immediately.
# shutdown -h now

Shutdown the system after 10 minutes.


# shutdown -h +10

Reboot the system using shutdown command.


# shutdown -r now

Force the filesystem check during reboot.


# shutdown -Fr now

19. ftp command examples Both ftp and secure ftp (sftp) has similar commands. To connect to a remote server and download multiple files, do the following.
$ ftp IP/hostname ftp> mget *.html

To view the file names located on the remote server before downloading, mls ftp command as shown below.
ftp> mls *.html /ftptest/features.html

/ftptest/index.html /ftptest/othertools.html /ftptest/samplereport.html /ftptest/usage.html

More ftp examples: FTP and SFTP Beginners Guide with 10 Examples 20. crontab command examples View crontab entry for a specific user
# crontab -u john -l

Schedule a cron job every 10 minutes.


*/10 * * * * /home/ramesh/check-disk-space

More crontab examples: Linux Crontab: 15 Awesome Cron Job Examples 21. service command examples Service command is used to run the system V init scripts. i.e Instead of calling the scripts located in the /etc/init.d/ directory with their full path, you can use the service command. Check the status of a service:
# service ssh status

Check the steatus of all the services.


service --status-all

Restart a service.
# service ssh restart

22. ps command examples ps command is used to display information about the processes that are running in the system. While there are lot of arguments that could be passed to a ps command, following are some of the common ones.

To view current running processes.


$ ps -ef | more

To view current running processes in a tree structure. H option stands for process hierarchy.
$ ps -efH | more

23. free command examples This command is used to display the free, used, swap memory available in the system. Typical free command output. The output is displayed in bytes.
$ free total cached Mem: 3566408 902960 -/+ buffers/cache: Swap: 4000176 used 1580220 473272 0 free 1986188 3093136 4000176 shared 0 buffers 203988

If you want to quickly check how many GB of RAM your system has use the -g option. -b option displays in bytes, -k in kilo bytes, -m in mega bytes.
$ free -g total cached Mem: 3 0 -/+ buffers/cache: Swap: 3 used 1 0 0 free 1 2 3 shared 0 buffers 0

If you want to see a total memory ( including the swap), use the -t switch, which will display a total line as shown below.
ramesh@ramesh-laptop:~$ free -t total used cached Mem: 3566408 1592148 912556 -/+ buffers/cache: 475332 Swap: 4000176 0 Total: 7566584 1592148 free 1974260 3091076 4000176 5974436 shared 0 buffers 204260

24. top command examples top command displays the top processes in the system ( by default sorted by cpu usage ). To sort top output by any column, Press O (upper-case O) , which will display all the possible columns that you can sort by as shown below.
Current Sort Field: P for window 1:Def Select sort field via field letter, type any other key to return a: PID count d: UID Function e: USER ........ = Process Id = User Id = User Name v: nDRT y: WCHAN z: Flags = Dirty Pages = Sleeping in = Task Flags

To displays only the processes that belong to a particular user use -u option. The following will show only the top processes that belongs to oracle user.
$ top -u oracle

More top examples: Can You Top This? 15 Practical Linux Top Command Examples 25. df command examples Displays the file system disk space usage. By default df -k displays output in bytes.
$ df -k Filesystem /dev/sda1 /dev/sda2 1K-blocks 29530400 120367992 Used Available Use% Mounted on 3233104 24797232 12% / 50171596 64082060 44% /home

df -h displays output in human readable form. i.e size will be displayed in GBs.
ramesh@ramesh-laptop:~$ df -h Filesystem Size Used Avail Use% Mounted on /dev/sda1 29G 3.1G 24G 12% / /dev/sda2 115G 48G 62G 44% /home

Use -T option to display what type of file system.


ramesh@ramesh-laptop:~$ df -T Filesystem Type 1K-blocks /dev/sda1 ext4 29530400 /dev/sda2 ext4 120367992 Used Available Use% Mounted on 3233120 24797216 12% / 50171596 64082060 44% /home

26. kill command examples Use kill command to terminate a process. First get the process id using ps -ef command, then use kill -9 to kill the running Linux process as shown below. You can also use killall, pkill, xkill to terminate a unix process.
$ ps -ef | grep vim ramesh 7243 7222 $ kill -9 7243 9 22:43 pts/2 00:00:00 vim

More kill examples: 4 Ways to Kill a Process kill, killall, pkill, xkill 27. rm command examples Get confirmation before removing the file.
$ rm -i filename.txt

It is very useful while giving shell metacharacters in the file name argument. Print the filename and get confirmation before removing the file.
$ rm -i file*

Following example recursively removes all files and directories under the example directory. This also removes the example directory itself.
$ rm -r example

28. cp command examples Copy file1 to file2 preserving the mode, ownership and timestamp.
$ cp -p file1 file2

Copy file1 to file2. if file2 exists prompt for confirmation before overwritting it.
$ cp -i file1 file2

29. mv command examples Rename file1 to file2. if file2 exists prompt for confirmation before overwritting it.

$ mv -i file1 file2

Note: mv -f is just the opposite, which will overwrite file2 without prompting. mv -v will print what is happening during file rename, which is useful while specifying shell metacharacters in the file name argument.
$ mv -v file1 file2

30. cat command examples You can view multiple files at the same time. Following example prints the content of file1 followed by file2 to stdout.
$ cat file1 file2

While displaying the file, following cat -n command will prepend the line number to each line of the output.
$ cat -n /etc/logrotate.conf 1 /var/log/btmp { 2 missingok 3 monthly 4 create 0660 root utmp 5 rotate 1 6 }

31. mount command examples To mount a file system, you should first create a directory and mount it as shown below.
# mkdir /u01 # mount /dev/sdb1 /u01

You can also add this to the fstab for automatic mounting. i.e Anytime system is restarted, the filesystem will be mounted.
/dev/sdb1 /u01 ext2 defaults 0 2

32. chmod command examples chmod command is used to change the permissions for a file or directory.

Give full access to user and group (i.e read, write and execute ) on a specific file.
$ chmod ug+rwx file.txt

Revoke all access for the group (i.e read, write and execute ) on a specific file.
$ chmod g-rwx file.txt

Apply the file permissions recursively to all the files in the sub-directories.
$ chmod -R ug+rwx file.txt

More chmod examples: 7 Chmod Command Examples for Beginners 33. chown command examples chown command is used to change the owner and group of a file. \ To change owner to oracle and group to db on a file. i.e Change both owner and group at the same time.
$ chown oracle:dba dbora.sh

Use -R to change the ownership recursively.


$ chown -R oracle:dba /home/oracle

34. passwd command examples Change your password from command line using passwd. This will prompt for the old password followed by the new password.
$ passwd

Super user can use passwd command to reset others password. This will not prompt for current password of the user.
# passwd USERNAME

Remove password for a specific user. Root user can disable password for a specific user. Once the password is disabled, the user can login without entering the password.
# passwd -d USERNAME

35. mkdir command examples Following example creates a directory called temp under your home directory.
$ mkdir ~/temp

Create nested directories using one mkdir command. If any of these directories exist already, it will not display any error. If any of these directories doesnt exist, it will create them.
$ mkdir -p dir1/dir2/dir3/dir4/

36. ifconfig command examples Use ifconfig command to view or configure a network interface on the Linux system. View all the interfaces along with status.
$ ifconfig -a

Start or stop a specific interface using up and down command as shown below.
$ ifconfig eth0 up $ ifconfig eth0 down

More ifconfig examples: Ifconfig: 7 Examples To Configure Network Interface 37. uname command examples Uname command displays important information about the system such as Kernel name, Host name, Kernel release number, Processor type, etc., Sample uname output from a Ubuntu laptop is shown below.
$ uname -a Linux john-laptop 2.6.32-24-generic #41-Ubuntu SMP Thu Aug 19 01:12:52 UTC 2010 i686 GNU/Linux

38. whereis command examples

When you want to find out where a specific Unix command exists (for example, where does ls command exists?), you can execute the following command.
$ whereis ls ls: /bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz

When you want to search an executable from a path other than the whereis default path, you can use -B option and give path as argument to it. This searches for the executable lsmk in the /tmp directory, and displays it, if it is available.
$ whereis -u -B /tmp -f lsmk lsmk: /tmp/lsmk

39. whatis command examples Whatis command displays a single line description about a command.
$ whatis ls ls (1) - list directory contents - configure a network interface

$ whatis ifconfig ifconfig (8)

40. locate command examples Using locate command you can quickly search for the location of a specific file (or group of files). Locate command uses the database created by updatedb. The example below shows all files in the system that contains the word crontab in it.
$ locate crontab /etc/anacrontab /etc/crontab /usr/bin/crontab /usr/share/doc/cron/examples/crontab2english.pl.gz /usr/share/man/man1/crontab.1.gz /usr/share/man/man5/anacrontab.5.gz /usr/share/man/man5/crontab.5.gz /usr/share/vim/vim72/syntax/crontab.vim

41. man command examples Display the man page of a specific command.
$ man crontab

When a man page for a command is located under more than one section, you can view the man page for that command from a specific section as shown below.
$ man SECTION-NUMBER commandname

Following 8 sections are available in the man page. 1. 2. 3. 4. 5. 6. 7. 8. General commands System calls C library functions Special files (usually devices, those found in /dev) and drivers File formats and conventions Games and screensavers Miscellaneous System administration commands and daemons

For example, when you do whatis crontab, youll notice that crontab has two man pages (section 1 and section 5). To view section 5 of crontab man page, do the following.
$ whatis crontab crontab (1) (V3) crontab (5) $ man 5 crontab - maintain crontab files for individual users - tables for driving cron

42. tail command examples Print the last 10 lines of a file by default.
$ tail filename.txt

Print N number of lines from the file named filename.txt


$ tail -n N filename.txt

View the content of the file in real time using tail -f. This is useful to view the log files, that keeps growing. The command can be terminated using CTRL-C.
$ tail -f log-file

More tail examples: 3 Methods To View tail -f output of Multiple Log Files in One Terminal

43. less command examples less is very efficient while viewing huge log files, as it doesnt need to load the full file while opening.
$ less huge-log-file.log

One you open a file using less command, following two keys are very helpful.
CTRL+F forward one window CTRL+B backward one window

More less examples: Unix Less Command: 10 Tips for Effective Navigation 44. su command examples Switch to a different user account using su command. Super user can switch to any other user without entering their password.
$ su - USERNAME

Execute a single command from a different account name. In the following example, john can execute the ls command as raj username. Once the command is executed, it will come back to johns account.
[john@dev-server]$ su - raj -c 'ls' [john@dev-server]$

Login to a specified user account, and execute the specified shell instead of the default shell.
$ su -s 'SHELLNAME' USERNAME

45. mysql command examples mysql is probably the most widely used open source database on Linux. Even if you dont run a mysql database on your server, you might end-up using the mysql command ( client ) to connect to a mysql database running on the remote server. To connect to a remote mysql database. This will prompt for a password.
$ mysql -u root -p -h 192.168.1.2

To connect to a local mysql database.


$ mysql -u root -p

If you want to specify the mysql root password in the command line itself, enter it immediately after -p (without any space). 46. yum command examples To install apache using yum.
$ yum install httpd

To upgrade apache using yum.


$ yum update httpd

To uninstall/remove apache using yum.


$ yum remove httpd

47. rpm command examples To install apache using rpm.


# rpm -ivh httpd-2.2.3-22.0.1.el5.i386.rpm

To upgrade apache using rpm.


# rpm -uvh httpd-2.2.3-22.0.1.el5.i386.rpm

To uninstall/remove apache using rpm.


# rpm -ev httpd

More rpm examples: RPM Command: 15 Examples to Install, Uninstall, Upgrade, Query RPM Packages 48. ping command examples Ping a remote host by sending only 5 packets.
$ ping -c 5 gmail.com

More ping examples: Ping Tutorial: 15 Effective Ping Command Examples 49. date command examples Set the system date:
# date -s "01/31/2010 23:59:53"

Once youve changed the system date, you should syncronize the hardware clock with the system date as shown below.
# hwclock systohc # hwclock --systohc utc

50. wget command examples The quick and effective method to download software, music, video from internet is using wget command.
$ wget http://prdownloads.sourceforge.net/sourceforge/nagios/nagios3.2.1.tar.gz

Download and store it with a different name.


$ wget -O taglist.zip http://www.vim.org/scripts/download_script.php? src_id=7701

Top 25 Best Linux Performance Monitoring and Debugging Tools


by Ramesh Natarajan on December 7, 2011

Ive compiled 25 performance monitoring and debugging tools that will be helpful when you are working on Linux environment. This list is not comprehensive or authoritative by any means. However this list has enough tools for you to play around and pick the one that is suitable your specific debugging and monitoring scenario. 1. SAR Using sar utility you can do two things: 1) Monitor system real time performance (CPU, Memory, I/O, etc) 2) Collect performance data in the background on an ongoing basis and do analysis on the historical data to identify bottlenecks. Sar is part of the sysstat package. The following are some of the things you can do using sar utility.

Collective CPU usage Individual CPU statistics Memory used and available Swap space used and available Overall I/O activities of the system Individual device I/O activities Context switch statistics Run queue and load average data Network statistics Report sar data from a specific time and lot more..

The following sar command will display the system CPU statistics 3 times (with 1 second interval).

The following sar -b command reports I/O statistics. 1 3 indicates that the sar -b will be executed for every 1 second for a total of 3 times.
$ sar -b 1 3 Linux 2.6.18-194.el5PAE (dev-db) CPU) 01:56:28 01:56:29 01:56:30 01:56:31 Average: PM PM PM PM tps 346.00 100.00 282.83 242.81 rtps 264.00 36.00 32.32 111.04 03/26/2011 wtps 82.00 64.00 250.51 131.77 bread/s 2208.00 304.00 258.59 925.75 _i686_ bwrtn/s 768.00 816.00 2537.37 1369.90 (8

More SAR examples: How to Install/Configure Sar (sysstat) and 10 Useful Sar Command 2. Tcpdump tcpdump is a network packet analyzer. Using tcpdump you can capture the packets and analyze it for any performance bottlenecks. The following tcpdump command example displays captured packets in ASCII.
$ tcpdump -A -i eth0 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes 14:34:50.913995 IP valh4.lell.net.ssh > yy.domain.innetbcp.net.11006: P 1457239478:1457239594(116) ack 1561461262 win 63652 E.....@.@..]..i...9...*.V...]...P....h....E...>{..U=...g. ......G..7\+KA....A...L. 14:34:51.423640 IP valh4.lell.net.ssh > yy.domain.innetbcp.net.11006: P 116:232(116) ack 1 win 63652 E.....@.@..\..i...9...*.V..*]...P....h....7......X..!....Im.S.g.u:*..O &....^#Ba... E..(R.@.|.....9...i.*...]...V..*P..OWp........

Using tcpdump you can capture packets based on several custom conditions. For example, capture packets that flow through a particular port, capture tcp communication between two specific hosts, capture packets that belongs to a specific protocol type, etc. More tcpdump examples: 15 TCPDUMP Command Examples 3. Nagios

Nagios is an open source monitoring solution that can monitor pretty much anything in your IT infrastructure. For example, when a server goes down it can send a notification to your sysadmin team, when a database goes down it can page your DBA team, when the a web server goes down it can notify the appropriate team. You can also set warning and critical threshold level for various services to help you proactively address the issue. For example, it can notify sysadmin team when a disk partition becomes 80% full, which will give enough time for the sysadmin team to work on adding more space before the issue becomes critical. Nagios also has a very good user interface from where you can monitor the health of your overall IT infrastructure. The following are some of the things you can monitor using Nagios:

Any hardware (servers, switches, routers, etc) Linux servers and Windows servers Databases (Oracle, MySQL, PostgreSQL, etc) Various services running on your OS (sendmail, nis, nfs, ldap, etc) Web servers Your custom application etc.

More Nagios examples: How to install and configure Nagios, monitor remote Windows machine, and monitor remote Linux server. 4. Iostat iostat reports CPU, disk I/O, and NFS statistics. The following are some of iostat command examples. Iostat without any argument displays information about the CPU usage, and I/O statistics about all the partitions on the system as shown below.
$ iostat Linux 2.6.32-100.28.5.el6.x86_64 (dev-db) avg-cpu: Device: sda %user 5.68 %nice %system %iowait 0.00 0.52 2.03 tps 194.72 Blk_read/s 1096.66 %steal 0.00 07/09/2011 %idle 91.76

Blk_wrtn/s Blk_read Blk_wrtn 1598.70 2719068704 3963827344

sda1 sda2 sdb sdb1 sdc sdc1

178.20 16.51 371.31 371.31 408.03 408.03

773.45 323.19 945.97 945.95 207.05 207.03

1329.09 1917686794 3295354888 269.61 801326686 668472456 1073.33 2345452365 2661206408 1073.33 2345396901 2661206408 972.42 513364213 2411023092 972.42 513308749 2411023092

By default iostat displays I/O data for all the disks available in the system. To view statistics for a specific device (For example, /dev/sda), use the option -p as shown below.
$ iostat -p sda Linux 2.6.32-100.28.5.el6.x86_64 (dev-db) avg-cpu: Device: sda sda2 sda1 %user 5.68 %nice %system %iowait 0.00 0.52 2.03 tps 194.69 336.38 821.89 Blk_read/s 1096.51 27.17 0.69 %steal 0.00 07/09/2011 %idle 91.76

Blk_wrtn/s Blk_read Blk_wrtn 1598.48 2719069928 3963829584 54.00 67365064 133905080 243.53 1720833 603892838

5. Mpstat mpstat reports processors statistics. The following are some of mpstat command examples. Option -A, displays all the information that can be displayed by the mpstat command as shown below. This is really equivalent to mpstat -I ALL -u -P ALL command.
$ mpstat -A Linux 2.6.32-100.28.5.el6.x86_64 (dev-db) _x86_64_ (4 CPU) 10:26:34 PM CPU %usr %steal %guest %idle 10:26:34 PM all 0.00 0.00 0.00 99.99 10:26:34 PM 0 0.01 0.00 0.00 99.98 10:26:34 PM 1 0.00 0.00 0.00 99.98 10:26:34 PM 2 0.00 0.00 0.00 100.00 10:26:34 PM 3 0.00 0.00 0.00 100.00 %nice 0.00 0.00 0.00 0.00 0.00 %sys %iowait 0.00 0.01 0.01 0.00 0.00 0.00 0.01 0.00 0.00 0.00 07/09/2011 %irq 0.00 0.00 0.00 0.00 0.00 %soft 0.00 0.00 0.00 0.00 0.00

10:26:34 10:26:34 10:26:34 10:26:34 10:26:34 10:26:34

PM PM PM PM PM PM

CPU all 0 1 2 3

intr/s 36.51 0.00 0.00 0.04 0.00

10:26:34 PM CPU 0/s 1/s 8/s 9/s 12/s 14/s 15/s 16/s 19/s 20/s 21/s 33/s NMI/s LOC/s SPU/s PMI/s PND/s RES/s CAL/s TLB/s TRM/s THR/s MCE/s MCP/s ERR/s MIS/s 10:26:34 PM 0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 7.47 0.00 0.00 0.00 0.00 0.02 0.00 0.00 0.00 0.00 0.00 0.00 0.00 10:26:34 PM 1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 4.90 0.00 0.00 0.00 0.00 0.03 0.00 0.00 0.00 0.00 0.00 0.00 0.00 10:26:34 PM 2 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.04 0.00 0.00 0.00 0.00 0.00 3.32 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 10:26:34 PM 3 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.

mpstat Option -P ALL, displays all the individual CPUs (or Cores) along with its statistics as shown below.
$ mpstat -P ALL Linux 2.6.32-100.28.5.el6.x86_64 (dev-db) _x86_64_ (4 CPU) 10:28:04 PM CPU %usr %steal %guest %idle 10:28:04 PM all 0.00 0.00 0.00 99.99 10:28:04 PM 0 0.01 0.00 0.00 99.98 10:28:04 PM 1 0.00 0.00 0.00 99.98 10:28:04 PM 2 0.00 0.00 0.00 100.00 10:28:04 PM 3 0.00 0.00 0.00 100.00 %nice 0.00 0.00 0.00 0.00 0.00 %sys %iowait 0.00 0.01 0.01 0.00 0.00 0.00 0.01 0.00 0.00 0.00 07/09/2011 %irq 0.00 0.00 0.00 0.00 0.00 %soft 0.00 0.00 0.00 0.00 0.00

6. Vmstat vmstat reports virtual memory statistics. The following are some of vmstat command examples.

vmstat by default will display the memory usage (including swap) as shown below.
$ vmstat procs -----------memory---------- ---swap-- -----io---- --system------cpu-----r b swpd free buff cache si so bi bo in cs us sy id wa st 0 0 305416 260688 29160 2356920 2 2 4 1 0 0 6 1 92 2 0 To execute vmstat every 2 seconds for 10 times, do the following. After executing 10 times, it will stop automatically. $ vmstat 2 10 procs -----------memory---------- ---swap-- -----io---- --system------cpu----r b swpd free buff cache si so bi bo in cs us sy id wa st 1 0 0 537144 182736 6789320 0 0 0 0 1 1 0 0 100 0 0 0 0 0 537004 182736 6789320 0 0 0 0 50 32 0 0 100 0 0 ..

iostat and vmstat are part of the sar utility. You should install sysstat package to get iostat and vmstat working. More examples: 24 iostat, vmstat and mpstat command Examples 7. PS Command Process is a running instance of a program. Linux is a multitasking operating system, which means that more than one process can be active at once. Use ps command to find out what processes are running on your system. ps command also give you lot of additional information about the running process which will help you identify any performance bottlenecks on your system. The following are few ps command examples. Use -u option to display the process that belongs to a specific username. When you have multiple username, separate them using a comma. The example below displays all the process that are owned by user wwwrun, or postfix.
$ ps -f -u wwwrun,postfix UID PID PPID C STIME TTY postfix 7457 7435 0 Mar09 ? TIME CMD 00:00:00 qmgr -l -t fifo -u

wwwrun prefork wwwrun prefork wwwrun prefork wwwrun prefork wwwrun prefork wwwrun prefork wwwrun prefork postfix

7495 7491 0 Mar09 ? -f /etc/apache2/httpd.conf 7496 7491 0 Mar09 ? -f /etc/apache2/httpd.conf 7497 7491 0 Mar09 ? -f /etc/apache2/httpd.conf 7498 7491 0 Mar09 ? -f /etc/apache2/httpd.conf 7499 7491 0 Mar09 ? -f /etc/apache2/httpd.conf 10078 7491 0 Mar09 ? -f /etc/apache2/httpd.conf 10082 7491 0 Mar09 ? -f /etc/apache2/httpd.conf 15677 7435 0 22:23 ?

00:00:00 /usr/sbin/httpd200:00:00 /usr/sbin/httpd200:00:00 /usr/sbin/httpd200:00:00 /usr/sbin/httpd200:00:00 /usr/sbin/httpd200:00:00 /usr/sbin/httpd200:00:00 /usr/sbin/httpd200:00:00 pickup -l -t fifo -u

The example below display the process Id and commands in a hierarchy. forest is an argument to ps command which displays ASCII art of process tree. From this tree, we can identify which is the parent process and the child processes it forked in a recursive manner.
$ ps -e -o pid,args --forest 468 \_ sshd: root@pts/7 514 | \_ -bash 17484 \_ sshd: root@pts/11 17513 | \_ -bash 24004 | \_ vi ./790310__11117/journal 15513 \_ sshd: root@pts/1 15522 | \_ -bash 4280 \_ sshd: root@pts/5 4302 | \_ -bash

More ps examples: 7 Practical PS Command Examples for Process Monitoring 8. Free Free command displays information about the physical (RAM) and swap memory of your system. In the example below, the total physical memory on this system is 1GB. The values displayed below are in KB.
# free total used Mem: 1034624 1006696 -/+ buffers/cache: Swap: 2031608 free shared buffers 27928 0 174136 216668 817956 0 2031608 cached 615892

The following example will display the total memory on your system including RAM and Swap. In the following command:

option m displays the values in MB option t displays the Total line, which is sum of physical and swap memory values option o is to hide the buffers/cache line from the above example.
total 1010 1983 2994 983 0 983 used 27 1983 2011 free shared 0 buffers 170

# free -mto cached Mem: 601 Swap: Total:

9. TOP Top command displays all the running process in the system ordered by certain columns. This displays the information real-time. You can kill a process without existing from top. Once youve located a process that needs to be killed, press k which will ask for the process id, and signal to send. If you have the privilege to kill that particular PID, it will get killed successfully.
PID to kill: 1309 Kill PID 1309 with signal [15]: PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1309 geek 23 0 2483m 1.7g 27m S 0 21.8 45:31.32 gagent 1882 geek 25 0 2485m 1.7g 26m S 0 21.7 22:38.97 gagent 5136 root 16 0 38040 14m 9836 S 0 0.2 0:00.39 nautilus

Use top -u to display a specific user processes only in the top command output.
$ top -u geek

While unix top command is running, press u which will ask for username as shown below.
Which user (blank for all): geek PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1309 geek 23 0 2483m 1.7g 27m S 0 21.8 45:31.32 gagent

1882 geek

25

0 2485m 1.7g

26m S

0 21.7

22:38.97 gagent

More top examples: 15 Practical Linux Top Command Examples 10. Pmap pmap command displays the memory map of a given process. You need to pass the pid as an argument to the pmap command. The following example displays the memory map of the current bash shell. In this example, 5732 is the PID of the bash shell.
$ pmap 5732 5732: -bash 00393000 104K 003b1000 1272K 00520000 8K 0053f000 12K 0084d000 76K 00c57000 32K 00c8d000 36K b7d6c000 2048K bfd10000 84K total 4796K

r-x-r-x-r-x-r-x-r-x-r-x-r-x-r---rw---

/lib/ld-2.5.so /lib/libc-2.5.so /lib/libdl-2.5.so /lib/libtermcap.so.2.0.8 /lib/libnsl-2.5.so /lib/libnss_nis-2.5.so /lib/libnss_files-2.5.so /usr/lib/locale/locale-archive [ stack ]

pmap -x gives some additional information about the memory maps.


$ pmap -x 5732 5732: -bash Address Kbytes RSS Anon Locked 00393000 104 003b1000 1272 00520000 8 0053f000 12 0084d000 76 00c57000 32 00c8d000 36 b7d6c000 2048 bfd10000 84 -------- ------- ------- ------- ------total kB 4796 -

Mode r-x-r-x-r-x-r-x-r-x-r-x-r-x-r---rw---

Mapping ld-2.5.so libc-2.5.so libdl-2.5.so libtermcap.so.2.0.8 libnsl-2.5.so libnss_nis-2.5.so libnss_files-2.5.so locale-archive [ stack ]

To display the device information of the process maps use pamp -d pid. 11. Netstat

Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc., The following are some netstat command examples. List all ports (both listening and non listening) using netstat -a as shown below.
# netstat -a | more Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 localhost:30037 *:* LISTEN udp 0 0 *:bootpc *:* Active UNIX domain sockets (servers Proto RefCnt Flags Type unix 2 [ ACC ] STREAM unix/X0 unix 2 [ ACC ] STREAM /var/run/acpid.socket and established) State I-Node LISTENING 6135 LISTENING 5140 Path /tmp/.X11-

Use the following netstat command to find out on which port a program is running.
# netstat -ap | grep ssh (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) tcp 1 0 dev-db:ssh 101.174.100.22:39213 CLOSE_WAIT tcp 1 0 dev-db:ssh 101.174.100.22:57643 CLOSE_WAIT -

Use the following netstat command to find out which process is using a particular port.
# netstat -an | grep ':80'

More netstat examples: 10 Netstat Command Examples 12. IPTraf IPTraf is a IP Network Monitoring Software. The following are some of the main features of IPTraf:

It is a console based (text-based) utility.

This displays IP traffic crossing over your network. This displays TCP flag, packet and byte counts, ICMP, OSPF packet types, etc. Displays extended interface statistics (including IP, TCP, UDP, ICMP, packet size and count, checksum errors, etc.) LAN module discovers hosts automatically and displays their activities Protocol display filters to view selective protocol traffic Advanced Logging features Apart from ethernet interface it also supports FDDI, ISDN, SLIP, PPP, and loopback You can also run the utility in full screen mode. This also has a text-based menu.

More info: IPTraf Home Page. IPTraf screenshot. 13. Strace Strace is used for debugging and troubleshooting the execution of an executable on Linux environment. It displays the system calls used by the process, and the signals received by the process. Strace monitors the system calls and signals of a specific program. It is helpful when you do not have the source code and would like to debug the execution of a program. strace provides you the execution sequence of a binary from start to end. Trace a Specific System Calls in an Executable Using Option -e Be default, strace displays all system calls for the given executable. The following example shows the output of strace for the Linux ls command.
$ strace ls execve("/bin/ls", ["ls"], [/* 21 vars */]) = 0 brk(0) = 0x8c31000 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) mmap2(NULL, 8192, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb78c7000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) open("/etc/ld.so.cache", O_RDONLY) = 3 fstat64(3, {st_mode=S_IFREG|0644, st_size=65354, ...}) = 0

To display only a specific system call, use the strace -e option as shown below.
$ strace -e open ls

open("/etc/ld.so.cache", O_RDONLY) = 3 open("/lib/libselinux.so.1", O_RDONLY) = 3 open("/lib/librt.so.1", O_RDONLY) = 3 open("/lib/libacl.so.1", O_RDONLY) = 3 open("/lib/libc.so.6", O_RDONLY) = 3 open("/lib/libdl.so.2", O_RDONLY) = 3 open("/lib/libpthread.so.0", O_RDONLY) = 3 open("/lib/libattr.so.1", O_RDONLY) = 3 open("/proc/filesystems", O_RDONLY|O_LARGEFILE) = 3 open("/usr/lib/locale/locale-archive", O_RDONLY|O_LARGEFILE) = 3 open(".", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|O_CLOEXEC) = 3

More strace examples: 7 Strace Examples to Debug the Execution of a Program in Linux 14. Lsof Lsof stands for ls open files, which will list all the open files in the system. The open files include network connection, devices and directories. The output of the lsof command will have the following columns:

COMMAND process name. PID process ID USER Username FD file descriptor TYPE node type of the file DEVICE device number SIZE file size NODE node number NAME full path of the file name.

To view all open files of the system, execute the lsof command without any parameter as shown below.
# lsof | more COMMAND PID USER NODE NAME init 1 root 2 / init 1 root 2 / init 1 root 983101 /sbin/init init 1 root 166798 /lib/ld-2.3.4.so FD cwd rtd txt mem TYPE DIR DIR REG REG DEVICE 8,1 8,1 8,1 8,1 SIZE 4096 4096 32684 106397

init 1 root mem 166799 /lib/tls/libc-2.3.4.so init 1 root mem 163964 /lib/libsepol.so.1 init 1 root mem 166811 /lib/libselinux.so.1 init 1 root 10u 972 /dev/initctl migration 2 root cwd 2 / skipped..

REG REG REG FIFO DIR

8,1 8,1 8,1 0,13 8,1

1454802 53736 56328

4096

To view open files by a specific user, use lsof -u option to display all the files opened by a specific user.
# lsof -u ramesh vi 7190 ramesh txt sshd 7163 ramesh 3u db:ssh->abc-12-12-12-12. REG IPv6 8,1 15088263 474608 475196 /bin/vi TCP dev-

To list users of a particular file, use lsof as shown below. In this example, it displays all users who are currently using vi.
# lsof /bin/vi COMMAND PID USER FD vi 7258 root txt vi 7300 ramesh txt TYPE DEVICE SIZE NODE NAME REG 8,1 474608 475196 /bin/vi REG 8,1 474608 475196 /bin/vi

15. Ntop Ntop is just like top, but for network traffic. ntop is a network traffic monitor that displays the network usage. You can also access ntop from browser to get the traffic information and network status. The following are some the key features of ntop:

Display network traffic broken down by protocols Sort the network traffic output based on several criteria Display network traffic statistics Ability to store the network traffic statistics using RRD Identify the identify of the users, and host os Ability to analyze and display IT traffic Ability to work as NetFlow/sFlow collector for routers and switches

Displays network traffic statistics similar to RMON Works on Linux, MacOS and Windows

More info: Ntop home page 16. GkrellM GKrellM stands for GNU Krell Monitors, or GTK Krell Meters. It is GTK+ toolkit based monitoring program, that monitors various sytem resources. The UI is stakable. i.e you can add as many monitoring objects you want one on top of another. Just like any other desktop UI based monitoring tools, it can monitor CPU, memory, file system, network usage, etc. But using plugins you can monitoring external applications. More info: GkrellM home page 17. w and uptime While monitoring system performance, w command will hlep to know who is logged on to the system.
$ w 09:35:06 up 21 days, 23:28, 2 users, load average: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root tty1 :0 24Oct11 21days 1:05 1:05 /usr/bin/Xorg :0 -nr -verbose ramesh pts/0 192.168.1.10 Mon14 0.00s 15.55s 0.26s sshd: localuser [priv] john pts/0 192.168.1.11 Mon07 0.00s 19.05s 0.20s sshd: localuser [priv] jason pts/0 192.168.1.12 Mon07 0.00s 21.15s 0.16s sshd: localuser [priv]

For each and every user who is logged on, it displays the following info:

Username tty info Remote host ip-address Login time of the user How long the user has been idle JCPU and PCUP The command of the current process the user is executing

Line 1 of the w command output is similar to the uptime command output. It displays the following:

Current time How long the system has been up and running Total number of users who are currently logged on the system Load average for the last 1, 5 and 15 minutes

If you want only the uptime information, use the uptime command.
$ uptime 09:35:02 up 106 days, 28 min, 0.05 2 users, load average: 0.08, 0.11,

Please note that both w and uptime command gets the information from the /var/run/utmp data file. 18. /proc /proc is a virtual file system. For example, if you do ls -l /proc/stat, youll notice that it has a size of 0 bytes, but if you do cat /proc/stat, youll see some content inside the file. Do a ls -l /proc, and youll see lot of directories with just numbers. These numbers represents the process ids, the files inside this numbered directory corresponds to the process with that particular PID. The following are the important files located under each numbered directory (for each process):

cmdline command line of the command. environ environment variables. fd Contains the file descriptors which is linked to the appropriate files. limits Contains the information about the specific limits to the process. mounts mount related information

The following are the important links under each numbered directory (for each process):

cwd Link to current working directory of the process. exe Link to executable of the process. root Link to the root directory of the process.

More /proc examples: Explore Linux /proc File System 19. KDE System Guard This is also called as KSysGuard. On Linux desktops that run KDE, you can use this tool to monitor system resources. Apart from monitoring the local system, this can also monitor remote systems. If you are running KDE desktop, go to Applications -> System -> System Monitor, which will launch the KSysGuard. You can also type ksysguard from the command line to launch it. This tool displays the following two tabs:

Process Table Displays all active processes. You can sort, kill, or change priority of the processes from here System Load Displays graphs for CPU, Memory, and Network usages. These graphs can be customized by right cliking on any of these graphs.

To connect to a remote host and monitor it, click on File menu -> Monitor Remote Machine -> specify the ip-address of the host, the connection method (for example, ssh). This will ask you for the username/password on the remote machine. Once connected, this will display the system usage of the remote machine in the Process Table and System Load tabs. 20. GNOME System Monitor On Linux desktops that run GNOME, you can use the this tool to monitor processes, system resources, and file systems from a graphical interface. Apart from monitoring, you can also use this UI tool to kill a process, change the priority of a process. If you are running GNOME desktop, go to System -> Administration -> System Monitor, which will launch the GNOME System Monitor. You can also type gnome-system-monitor from the command line to launch it. This tool has the following four tabs:

System Displays the system information including Linux distribution version, system resources, and hardware information.

Processes Displays all active processes that can be sorted based on various fields Resources Displays CPU, memory and network usages File Systems Displays information about currently mounted file systems

More info: GNOME System Monitor home page 21. Conky Conky is a system monitor or X. Conky displays information in the UI using what it calls objects. By default there are more than 250 objects that are bundled with conky, which displays various monitoring information (CPU, memory, network, disk, etc.). It supports IMAP, POP3, several audio players. You can monitor and display any external application by craeting your own objects using scripting. The monitoring information can be displays in various format: Text, graphs, progress bars, etc. This utility is extremly configurable. More info: Conky screenshots 22. Cacti Cacti is a PHP based UI frontend for the RRDTool. Cacti stores the data required to generate the graph in a MySQL database. The following are some high-level features of Cacti:

Ability to perform the data gathering and store it in MySQL database (or round robin archives) Several advanced graphing featurs are available (grouping of GPRINT graph items, auto-padding for graphs, manipulate graph data using CDEF math function, all RRDTool graph items are supported) The data source can gather local or remote data for the graph Ability to fully customize Round robin archive (RRA) settings User can define custom scripts to gather data SNMP support (php-snmp, ucd-snmp, or net-snmp) for data gathering Built-in poller helps to execute custom scripts, get SNMP data, update RRD files, etc. Highly flexible graph template features User friendly and customizable graph display options

Create different users with various permission sets to access the cacti frontend Granular permission levels can be set for the individual user and lot more..

More info: Cacti home page 23. Vnstat vnstat is a command line utility that displays and logs network traffic of the interfaces on your systems. This depends on the network statistics provided by the kernel. So, vnstat doesnt add any additional load to your system for monitoring and logging the network traffic. vnstat without any argument will give you a quick summary with the following info:

The last time when the vnStat datbase located under /var/lib/vnstat/ was updated From when it started collecting the statistics for a specific interface The network statistic data (bytes transmitted, bytes received) for the last two months, and last two days.

# vnstat Database updated: Sat Oct 15 11:54:00 2011 eth0 since 10/01/11 rx: monthly rx | tx | total | ------------------------+-------------+------------+--------------Sep '11 12.90 MiB | 6.90 MiB | 19.81 MiB | kbit/s Oct '11 12.89 MiB | 6.94 MiB | 19.82 MiB | kbit/s ------------------------+-------------+------------+--------------estimated 29 MiB | 14 MiB | 43 MiB | daily rx | tx | total | ------------------------+-------------+------------+--------------avg. rate avg. rate 0.14 0.15 12.89 MiB tx: 6.94 MiB total: 19.82 MiB

yesterday 4.30 MiB | 2.42 MiB | 6.72 MiB | kbit/s today 2.03 MiB | 1.07 MiB | 3.10 MiB | kbit/s ------------------------+-------------+------------+--------------estimated 4 MiB | 2 MiB | 6 MiB |

0.64 0.59

Use vnstat -t or vnstat top10 to display all time top 10 traffic days.
$ vnstat --top10 eth0 / top 10 avg.

# day rx | tx | total | rate -----------------------------+-------------+------------+--------------1 10/12/11 4.30 MiB | 2.42 MiB | 6.72 MiB | kbit/s 2 10/11/11 4.07 MiB | 2.17 MiB | 6.24 MiB | kbit/s 3 10/10/11 2.48 MiB | 1.28 MiB | 3.76 MiB | kbit/s .... -----------------------------+-------------+------------+---------------

0.64 0.59 0.36

More vnstat Examples: How to Monitor and Log Network Traffic using VNStat 24. Htop htop is a ncurses-based process viewer. This is similar to top, but is more flexible and user friendly. You can interact with the htop using mouse. You can scroll vertically to view the full process list, and scroll horizontally to view the full command line of the process. htop output consists of three sections 1) header 2) body and 3) footer. Header displays the following three bars, and few vital system information. You can change any of these from the htop setup menu.

CPU Usage: Displays the %used in text at the end of the bar. The bar itself will show different colors. Low-priority in blue, normal in green, kernel in red. Memory Usage

Swap Usage

Body displays the list of processes sorted by %CPU usage. Use arrow keys, page up, page down key to scoll the processes. Footer displays htop menu commands. More info: HTOP Screenshot and Examples 25. Socket Statistics SS ss stands for socket statistics. This displays information that are similar to netstat command. To display all listening sockets, do ss -l as shown below.
$ ss -l Recv-Q Send-Q 0 100 0 128 0 100 0 128 0 64 Local Address:Port :::8009 :::sunrpc :::webcache :::ssh :::nrpe Peer Address:Port :::* :::* :::* :::* :::*

The following displays only the established connection.


$ ss -o state established Recv-Q Send-Q Local Address:Port Peer Address:Port 0 52 192.168.1.10:ssh 192.168.2.11:55969 (on,414ms,0)

timer:

The following displays socket summary statistics. This displays the total number of sockets broken down by the type.
$ ss -s Total: 688 (kernel 721) TCP: 16 (estab 1, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 11 Transport * RAW UDP TCP INET FRAG Total 721 0 13 16 29 0 IP 0 10 7 17 0 IPv6 0 3 9 12 0

Unix Shell Tips: Change Login Shell From Bash to Others


by Ramesh Natarajan on October 9, 2009 Question: How do I find out what Unix shell Im currently running? Can you also explain how can I change my Unix shell both temporarily and permanently? (For example, from bash to tsh). Answer: You can achieve these using $0, exec, chsh -s. In this article, let us review how to do these in detail. 1. What is my current Unix shell? Use echo $0 command to get your current shell name as shown below.
$ echo $0 /bin/bash

2. How to change my current shell to another type temporarily ? Use exec command to change your shell temporarily as shown below.
$ echo $0 /bin/bash $ exec /bin/sh $ echo $0 /bin/sh

Note: The above change is temporary. When you relogin, youll go back to the original shell. 3. How to change my current shell to another type permanently ? To change your shell permanently, use chsh command as shown below.
$ chsh -s /bin/sh Password:

Note: The above change is permanent. Even after relogin, youll see only the new shell. 4. How can I find out all available shells in my system ? All available shells are located in the /etc/shells file.
$ cat /etc/shells # /etc/shells: valid login shells /bin/csh /bin/sh /usr/bin/es /usr/bin/ksh /bin/ksh /usr/bin/rc /usr/bin/tcsh /bin/tcsh /usr/bin/esh /bin/dash /bin/bash /bin/rbash /usr/bin/screen /bin/ksh93

For changing your login shell, you can do only from the above output. But for changing the current shell, you can go to any available shell. 5. Installing New Shell You can install a new shell (for example, ksh) as shown below. After installing new shell, you can use it as your permanent login shell, or temporary shell for your command line operations.
$ sudo apt-get install ksh

6 Steps to Secure Your Home Wireless Network


by Ramesh Natarajan on August 7, 2008

Most of you might have enabled wireless encryption, which is only one of the 6 steps mentioned in this article to make your wireless network safe and secure from hackers. The screenshots mentioned below are from Linksys wireless router. But, youll find similar options for all the 6 steps mentioned below in wireless routers from any other vendors. Apart from these 6 steps to secure your wireless router, also make sure your wireless router firmware is up-to-date. Refer to our 4 easy steps to upgrade linksys wireless router firmware article for detailed instructions on how to upgrade your router firmware. 1. Enable Encryption Let us start with the basics. Most of the wireless router has the encryption disabled by default. Make sure to enable either WPA or WPA2 wireless encryption. Click on Wireless -> Wireless Security , to enable the encryption and assign a password as shown in Fig-1. Following are the different wireless encryption options available.

WEP (Wired Equivalent Protection) 64-bit and 128-bit: WEP is an old wireless encryption standard. Never use WEP encryption, which can be hacked within seconds. WPA (Wi-Fi Protected Access): WPA-PSK is also refered as WPAPersonal. This is a new version of wireless encryption standard and more secure than WEP. Most of the wireless adapters on your laptop will support WPA. WPA2: This is the latest wireless encryption standard that provides the best encryption. Always use WPA2, if both your wireless router and laptop wireless adapter supports it.

Fig-1 Enable Wireless Encryption 2. Change the SSID name SSID (Service Set Identifier) refers to the name of your wireless connection, that you see on the Available Wireless Connections list from your laptop while connecting. Changing the wireless name itself doesnt offer any protection, but usually discourages a hacker, as they know that youve taken some steps to secure your wireless connection. Click on Wireless -> Basic wireless settings -> Change the Wireless Network Name (SSID):, as shown in the Fig-2. 3. Disable SSID broadcast You can avoid your wireless name from getting displayed on Available Wireless Connections on all your neighbors laptop. This can be done by instructing the wireless router not to broadcast the name to everybody. Once youve disabled the SSID broadcast, the first time when someone wants to connect to your wireless network, you need to provide the name to them. Click on Wireless -> Basic wireless settings -> Click on the Disable radio-button next to Wireless SSID Broadcast, as shown in Fig-2.

Fig-2: Change SSID Name and Disable Broadcast 4. Enable MAC filtering Even after you have performed the above item#1 #3, a very determined hacker may still get access to your network. The next security step is to allow wireless access only to your trusted laptops, by allowing wireless connection only to known MAC address. MAC (Media Access Control) address is an unique identifier attached to most network adapters. In this case, this should be the unique identifier of your laptop wireless adapter. On Linux, do ifconfig from the command prompt to get wireless hardware address. On windows, do ipconfig /all from the command prompt to identify the MAC address as shown below.
C:>ipconfig /all Ethernet adapter Wireless Network Connection-specific DNS Suffix . Description . . . . . . . . . . . Physical Address. . . . . . . . . Connection: : socal.rr.com : Dell Wireless 1390 WLAN Mini-Card : 00:1A:92:2B:70:B6

Click on Wireless -> Wireless MAC filter -> Click on Enable radio-button next to Wireless MAC filter -> Click on Permit only PCs listed to access the wireless network radio-button, as shown in Fig-3.

Fig-3 Enable Wireless MAC Filter

Click on Edit MAC filter list and add the MAC address of your laptop to this list. If you want to allow access to more than one laptop, add the MAC address of all the laptops to this list as shown in Fig-4 and click on Save Settings.

Fig-4 Add MAC Address to the list 5. Change password for Web Access The default password for wireless web access are the same for the specific model of a wireless router assigned by the manufacturer. Change the default password of the wireless router web access to a strong password. Follow The Ultimate Guide For Creating Strong Passwords to choose a strong password. Click on Administration -> Management, to change the password as shown in Fig-5 below.

Fig-5 Change password and disable wireless web access 6. Disable administrative access through web As a final step, make sure to disable web administrative access through wireless. Once you do this, to make any configuration changes to the wireless router, you can always use ethernet cable connection from your laptop to configure the wireless. Click on Administration -> Management -> Disable radio-button next to Wireless Access Web, as shown in Fig-5 above.

< How to set file permissions - symbolic mode >


You can set file permissions with the chmod command. Both the root user and the file's owner can set file permissions. chmod has two modes, symbolic and numeric. The symbolic mode is pretty easy to remember. First, you decide if you set permissions for the user (u), the group (g), others (o), or all of the three (a). Then, you either add a permission (+), remove it (-), or wipe out the previous permissions and add a new one (=). Next, you decide if you set the read permission (r), write permission (w), or execute permission (x). Last, you'll tell chmod which file's permissions you want to change. Let's have a couple of examples. Suppose we have a regular file called testfile, and the file has full access permissions for all the groups (long directory listing would show -rwxrwxrwx as the file's permissions). Wipe out all the permissions but add read permission for everybody:
$ chmod a=r testfile

After the command, the file's permissions would be -r--r--r--

Add execute permissions for group:


$ chmod g+x testfile

Now, the file's permissions would be -r--r-xr-Add both write and execute permissions for the file's owner. Note how you can set more than one permission at the same time:
$ chmod u+wx testfile

After this, the file permissions will be -rwxr-xr-Remove the execute permission from both the file's owner and group. Note, again, how you can set them both at once:
$ chmod ug-x testfile Now, the permissions are -rw-r--r--

As a summary, have a look at this quick reference for setting file permissions in symbolic mode:
Which user? u user/owner g group o other a all What to do? + add this permission remove this permission set exactly this permission

Which permissions? r read

w write

x execute

< How to set file permissions - numeric mode >


The other mode in which chmod can be used is the numeric mode. In the numeric mode, the file permissions aren't represented by characters. Instead, they are represented by a three-digit octal number. 4 = read (r) 2 = write (w) 1 = execute (x) 0 = no permission (-) To get the permission bits you want, you add up the numbers accordingly. For example, the rwx permissions would be 4+2+1=7, rx would be 4+1=5, and rw would be 4+2=6. Because you set separate permissions for the owner, group, and others, you'll need a three-digit number representing the permissions of all these groups. Let's have an example. $ chmod 755 testfile This would change the testfile's permissions to -rwxr-xr-x. The owner would have full read, write, and execute permissions (7=4+2+1), the group would have read and execute permissions (5=4+1), and the world would have the read and execute permissions as well. Let's have another example: $ chmod 640 testfile In this case, testfile's permissions would be -rw-r-----. The owner would have read and write permissions (6=4+2), the group would have read permissions only (4), and the others wouldn't have any access permissions (0). The numeric mode may not be as straightforward as the symbolic mode, but with the numeric mode, you can more quickly and efficiently set the file permissions. This quick reference for setting file permissions in numeric mode might help:
Which number? 0 1 2 ----x -w-

3 4 5 6 7

-wx r-r-x rwrwx

Permissions
The Unix operating system (and likewise, Linux) differs from other computing environments in that it is not only a multitasking system but it is also a multi-user system as well. What exactly does this mean? It means that more than one user can be operating the computer at the same time. While your computer will only have one keyboard and monitor, it can still be used by more than one user. For example, if your computer is attached to a network, or the Internet, remote users can log in via telnet or ssh (secure shell) and operate the computer. In fact, remote users can execute X applications and have the graphical output displayed on a remote computer. The X Windows system supports this. The multi-user capability of Unix is not a recent "innovation," but rather a feature that is deeply ingrained into the design of the operating system. If you remember the environment in which Unix was created, this makes perfect sense. Years ago before computers were "personal," they were large, expensive, and centralized. A typical university computer system consisted of a large mainframe computer located in some building on campus and terminals were located throughout the campus, each connected to the large central computer. The computer would support many users at the same time. In order to make this practical, a method had to be devised to protect the users from each other. After all, you could not allow the actions of one user to crash the computer, nor could you allow one user to interfere with the files belonging to another user. This lesson will cover the following commands:
chmod - modify file access rights su - temporarily become the superuser

chown - change file ownership chgrp - change a file's group ownership

File permissions
Linux uses the same permissions scheme as Unix. Each file and directory on your system is assigned access rights for the owner of the file, the members of a group of related users, and everybody else. Rights can be assigned to read a file, to write a file, and to execute a file (i.e., run the file as a program). To see the permission settings for a file, we can use the ls command as follows:
[me@linuxbox me]$ ls -l some_file

-rw-rw-r-- 1 me

me

1097374 Sep 26 18:48 some_file

We can determine a lot from examining the results of this command:


The file "some_file" is owned by user "me" User "me" has the right to read and write this file The file is owned by the group "me" Members of the group "me" can also read and write this file Everybody else can read this file

Let's try another example. We will look at the bash program which is located in the /bin directory:
[me@linuxbox me]$ ls -l /bin/bash

-rwxr-xr-x 1 root root

316848 Feb 27

2000 /bin/bash

Here we can see:


The file "/bin/bash" is owned by user "root" The superuser has the right to read, write, and execute this file The file is owned by the group "root" Members of the group "root" can also read and execute this file Everybody else can read and execute this file

In the diagram below, we see how the first portion of the listing is interpreted. It consists of a character indicating the file type, followed by three sets of three characters that convey the reading, writing and execution permission for the owner, group, and everybody else.

chmod
The chmod command is used to change the permissions of a file or directory. To use it, you specify the desired permission settings and the file or files that you wish to modify. There are two ways to specify the permissions, but I am only going to teach one way. It is easy to think of the permission settings as a series of bits (which is how the computer thinks about them). Here's how it works:
rwx rwx rwx = 111 111 111 rw- rw- rw- = 110 110 110 rwx --- --- = 111 000 000 and so on... rwx rwr-x r-= = = = 111 110 101 100 in in in in binary binary binary binary = = = = 7 6 5 4

Now, if you represent each of the three sets of permissions (owner, group, and other) as a single digit, you have a pretty convenient way of expressing the possible permissions settings. For example, if we wanted to set some_file to have read and write permission for the owner, but wanted to keep the file private from others, we would:
[me@linuxbox me]$ chmod 600 some_file

Here is a table of numbers that covers all the common settings. The ones beginning with "7" are used with programs (since they enable execution) and the rest are for other kinds of files.
Valu e Meaning

777 755

(rwxrwxrwx) No restrictions on permissions. Anybody may do anything. Generally not a desirable setting. (rwxr-xr-x) The file's owner may read, write, and execute the file. All others may read and execute the file. This setting is common for programs that are used by all users. (rwx------) The file's owner may read, write, and execute the file. Nobody else has any rights. This setting is useful for programs that only the owner may use and must be kept private from others. (rw-rw-rw-) All users may read and write the file. (rw-r--r--) The owner may read and write a file, while all others may only read the file. A common setting for data files that everybody may read, but only the owner may change. (rw-------) The owner may read and write a file. All others have no rights. A common setting for data files that the owner wants to keep private.

700 666 644 600

Directory permissions
The chmod command can also be used to control the access permissions for directories. In most ways, the permissions scheme for directories works the same way as they do with files. However, the execution permission is used in a different way. It provides control for access to file listing and other things. Here are some useful settings for directories:
Valu e Meaning

777

(rwxrwxrwx) No restrictions on permissions. Anybody may list files, create new files in the directory and delete files in the directory. Generally not a good setting. (rwxr-xr-x) The directory owner has full access. All others may list the directory, but cannot create files nor delete them. This setting is common for directories that you wish to share with other users. (rwx------) The directory owner has full access. Nobody else has any rights. This setting is useful for directories that only the owner may use and must be kept private from others.

755

700

Becoming the superuser for a short while


It is often useful to become the superuser to perform important system administration tasks, but as you have been warned (and not just by me!), you should not stay logged on as the superuser. In most distributions, there is a program that can give you temporary access to the superuser's privileges. This program is called su (short for substitute user) and can be used in those cases when you need to be the superuser for a small number of tasks. To become the superuser, simply type the su command. You will be prompted for the superuser's password:
[me@linuxbox me]$ su Password: [root@linuxbox me]#

After executing the su command, you have a new shell session as the superuser. To exit the superuser session, type exit and you will return to your previous session. In some distributions, most notably Ubuntu, an alternate method is used. Rather than using su, these systems employ the sudo command instead. With sudo, one or more users are granted superuser privileges on an as needed basis. To execute a command as the superuser, the desired command is simply preceeded with the sudo command. After the command is entered, the user is prompted for the user's password rather than the superuser's:
[me@linuxbox me]$ sudo some_command Password: [me@linuxbox me]$

Changing file ownership


You can change the owner of a file by using the chown command. Here's an example: Suppose I wanted to change the owner of some_file from "me" to "you". I could:
[me@linuxbox me]$ su Password: [root@linuxbox me]# chown you some_file [root@linuxbox me]# exit [me@linuxbox me]$

Notice that in order to change the owner of a file, you must be the superuser. To do this, our example employed the su command, then we executed chown, and finally we typed exit to return to our previous session.
chown

works the same way on directories as it does on files.

Changing group ownership


The group ownership of a file or directory may be changed with chgrp. This command is used like this:

[me@linuxbox me]$ chgrp new_group some_file

In the example above, we changed the group ownership of some_file from its previous group to "new_group". You must be the owner of the file or directory to perform a chgrp.

RPM Command: 15 Examples to Install, Uninstall, Upgrade, Query RPM Packages

RPM command is used for installing, uninstalling, upgrading, querying, listing, and checking RPM packages on your Linux system. RPM stands for Red Hat Package Manager. With root privilege, you can use the rpm command with appropriate options to manage the RPM software packages. In this article, let us review 15 practical examples of rpm command. Let us take an rpm of Mysql Client and run through all our examples.

1. Installing a RPM package Using rpm -ivh


RPM filename has packagename, version, release and architecture name. For example, In the MySQL-client-3.23.57-1.i386.rpm file:

MySQL-client Package Name 3.23.57 Version 1 Release

i386 Architecture

When you install a RPM, it checks whether your system is suitable for the software the RPM package contains, figures out where to install the files located inside the rpm package, installs them on your system, and adds that piece of software into its database of installed RPM packages. The following rpm command installs Mysql client package.
# rpm -ivh MySQL-client-3.23.57-1.i386.rpm Preparing... ########################################### [100%] 1:MySQL-client ########################################### [100%]

rpm command and options


-i : install a package -v : verbose -h : print hash marks as the package archive is unpacked.

You can also use dpkg on Debian, pkgadd on Solaris, depot on HP-UX to install packages.

2. Query all the RPM Packages using rpm -qa


You can use rpm command to query all the packages installed in your system.
# rpm -qa cdrecord-2.01-10.7.el5 bluez-libs-3.7-1.1 setarch-2.0-1.1 . .

-q query operation -a queries all installed packages

To identify whether a particular rpm package is installed on your system, combine rpm and grep command as shown below. Following command checks whether cdrecord package is installed on your system.
# rpm -qa | grep 'cdrecord'

3. Query a Particular RPM Package using rpm -q


The above example lists all currently installed package. After installation of a package to check the installation, you can query a particular package and verify as shown below.
# rpm -q MySQL-client MySQL-client-3.23.57-1

# rpm -q MySQL package MySQL is not installed

Note: To query a package, you should specify the exact package name. If the package name is incorrect, then rpm command will report that the package is not installed.

4. Query RPM Packages in a various format using rpm queryformat


Rpm command provides an option queryformat, which allows you to give the header tag names, to list the packages. Enclose the header tag with in {}.
# rpm -qa --queryformat '%{name-%{version}-%{release} %{size}\n' cdrecord-2.01-10.7 12324 bluez-libs-3.7-1.1 5634 setarch-2.0-1.1 235563 . . #

5. Which RPM package does a file belong to? Use rpm -qf
Let us say, you have list of files and you would want to know which package owns all these files. rpm command has options to achieve this. The following example shows that /usr/bin/mysqlaccess file is part of the MySQL-client3.23.57-1 rpm.
# rpm -qf /usr/bin/mysqlaccess MySQL-client-3.23.57-1

-f : file name

6. Locate documentation of a package that owns file using rpm -qdf


Use the following to know the list of documentations, for a package that owns a file. The following command, gives the location of all the manual pages related to mysql package.
# rpm -qdf /usr/bin/mysqlaccess /usr/share/man/man1/mysql.1.gz /usr/share/man/man1/mysqlaccess.1.gz /usr/share/man/man1/mysqladmin.1.gz /usr/share/man/man1/mysqldump.1.gz /usr/share/man/man1/mysqlshow.1.gz

-d : refers documentation.

7. Information about Installed RPM Package using rpm -qi

rpm command provides a lot of information about an installed pacakge using rpm -qi as shown below:
# rpm -qi MySQL-client Name : MySQL-client Relocations: (not relocatable) Version : 3.23.57 Vendor: MySQL AB Release : 1 Build Date: Mon 09 Jun 2003 11:08:28 PM CEST Install Date: Mon 06 Feb 2010 03:19:16 AM PST Build Host: build.mysql.com Group : Applications/Databases Source RPM: MySQL-3.23.571.src.rpm Size : 5305109 License: GPL / LGPL Signature : (none) Packager : Lenz Grimmer URL : http://www.mysql.com/ Summary : MySQL - Client Description : This package contains the standard MySQL clients.

If you have an RPM file that you would like to install, but want to know more information about it before installing, you can do the following:
# rpm -qip MySQL-client-3.23.57-1.i386.rpm Name : MySQL-client Relocations: (not relocatable) Version : 3.23.57 Vendor: MySQL AB Release : 1 Build Date: Mon 09 Jun 2003 11:08:28 PM CEST Install Date: (not installed) Build Host: build.mysql.com Group : Applications/Databases Source RPM: MySQL-3.23.571.src.rpm Size : 5305109 License: GPL / LGPL Signature : (none) Packager : Lenz Grimmer URL : http://www.mysql.com/ Summary : MySQL - Client Description : This package contains the standard MySQL clients.

-i : view information about an rpm -p : specify a package name

8. List all the Files in a Package using rpm -qlp


To list the content of a RPM package, use the following command, which will list out the files without extracting into the local directory folder.
$ rpm -qlp ovpc-2.1.10.rpm /usr/bin/mysqlaccess /usr/bin/mysqldata /usr/bin/mysqlperm . . /usr/bin/mysqladmin

q : query the rpm file l : list the files in the package p : specify the package name

You can also extract files from RPM package using rpm2cpio as we discussed earlier.

9. List the Dependency Packages using rpm -qRP


To view the list of packages on which this package depends,
# rpm -qRp MySQL-client-3.23.57-1.i386.rpm /bin/sh /usr/bin/perl

10. Find out the state of files in a package using rpm -qsp
The following command is to find state (installed, replaced or normal) for all the files in a RPM package.
# rpm -qsp MySQL-client-3.23.57-1.i386.rpm normal /usr/bin/msql2mysql normal /usr/bin/mysql normal /usr/bin/mysql_find_rows normal /usr/bin/mysqlaccess normal /usr/bin/mysqladmin normal /usr/bin/mysqlbinlog normal /usr/bin/mysqlcheck normal /usr/bin/mysqldump normal /usr/bin/mysqlimport normal /usr/bin/mysqlshow normal /usr/share/man/man1/mysql.1.gz normal /usr/share/man/man1/mysqlaccess.1.gz normal /usr/share/man/man1/mysqladmin.1.gz normal /usr/share/man/man1/mysqldump.1.gz normal /usr/share/man/man1/mysqlshow.1.gz

11. Verify a Particular RPM Package using rpm -Vp


Verifying a package compares information about the installed files in the package with information about the files taken from the package metadata stored in the rpm database. In the following command, -V is for verification and -p option is used to specify a package name to verify.
# rpm -Vp MySQL-client-3.23.57-1.i386.rpm S.5....T c /usr/bin/msql2mysql S.5....T c /usr/bin/mysql S.5....T c /usr/bin/mysql_find_rows S.5....T c /usr/bin/mysqlaccess

The character in the above output denotes the following:

S file Size differs M Mode differs (includes permissions and file type) 5 MD5 sum differs D Device major/minor number mismatch L readlink(2) path mismatch U User ownership differs G Group ownership differs T mTime differs

12. Verify a Package Owning file using rpm -Vf


The following command verify the package which owns the given filename.
# rpm -Vf /usr/bin/mysqlaccess S.5....T c /usr/bin/mysql #

13. Upgrading a RPM Package using rpm -Uvh


Upgrading a package is similar to installing one, but RPM automatically un-installs existing versions of the package before installing the new one. If an old version of the package is not found, the upgrade option will still install it.
# rpm -Uvh MySQL-client-3.23.57-1.i386.rpm Preparing... ########################################### [100%] 1:MySQL-client ###########################################

14. Uninstalling a RPM Package using rpm -e


To remove an installed rpm package using -e as shown below. After uninstallation, you can query using rpm -qa and verify the uninstallation.
# rpm -ev MySQL-client

15. Verifying all the RPM Packages using rpm -Va


The following command verifies all the installed packages.
# rpm -Va S.5....T c S.5....T c S.5....T c S.5....T c . . S.5....T c S.5....T c /etc/issue /etc/issue.net /var/service/imap/ssl/seed /home/httpd/html/horde/ingo/config/backends.php /home/httpd/html/horde/ingo/config/prefs.php /etc/printcap

The Ultimate Tar Command


1. Creating an archive using tar command
Creating an uncompressed tar archive using option cvf

This is the basic command to create a tar archive.


$ tar cvf archive_name.tar dirname/

In the above command:


c create a new archive v verbosely list files which are processed. f following is the archive file name

Creating a tar gzipped archive using option cvzf

The above tar cvf option, does not provide any compression. To use a gzip compression on the tar archive, use the z option as shown below.
$ tar cvzf archive_name.tar.gz dirname/

z filter the archive through gzip

Note: .tgz is same as .tar.gz Note: I like to keep the cvf (or tvf, or xvf) option unchanged for all archive creation (or view, or extract) and add additional option at the end, which is easier to remember. i.e cvf for archive creation, cvfz for compressed gzip archive creation, cvfj for compressed bzip2 archive creation etc., For this method to work properly, dont give in front of the options.
Creating a bzipped tar archive using option cvjf

Create a bzip2 tar archive as shown below:


$ tar cvfj archive_name.tar.bz2 dirname/

j filter the archive through bzip2

gzip vs bzip2: bzip2 takes more time to compress and decompress than gzip. bzip2 archival size is less than gzip. Note: .tbz and .tb2 is same as .tar.bz2

2. Extracting (untar) an archive using tar command


Extract a *.tar file using option xvf

Extract a tar file using option x as shown below:


$ tar xvf archive_name.tar

x extract files from archive

Extract a gzipped tar archive ( *.tar.gz ) using option xvzf

Use the option z for uncompressing a gzip tar archive.


$ tar xvfz archive_name.tar.gz

Extracting a bzipped tar archive ( *.tar.bz2 ) using option xvjf

Use the option j for uncompressing a bzip2 tar archive.


$ tar xvfj archive_name.tar.bz2

Note: In all the above commands v is optional, which lists the file being processed.

3. Listing an archive using tar command


View the tar archive file content without extracting using option tvf

You can view the *.tar file content before extracting as shown below.
$ tar tvf archive_name.tar

View the *.tar.gz file content without extracting using option tvzf

You can view the *.tar.gz file content before extracting as shown below.
$ tar tvfz archive_name.tar.gz

View the *.tar.bz2 file content without extracting using option tvjf

You can view the *.tar.bz2 file content before extracting as shown below.
$ tar tvfj archive_name.tar.bz2

4. Listing out the tar file content with less command

When the number of files in an archive is more, you may pipe the output of tar to less. But, you can also use less command directly to view the tar archive output, as explained in one of our previous article Open & View 10 Different File Types with Linux Less Command The Ultimate Power of Less.

5. Extract a single file from tar, tar.gz, tar.bz2 file


To extract a specific file from a tar archive, specify the file name at the end of the tar xvf command as shown below. The following command extracts only a specific file from a large tar file.
$ tar xvf archive_file.tar /path/to/file

Use the relevant option z or j according to the compression method gzip or bzip2 respectively as shown below.
$ tar xvfz archive_file.tar.gz /path/to/file $ tar xvfj archive_file.tar.bz2 /path/to/file

6. Extract a single directory from tar, tar.gz, tar.bz2 file


To extract a single directory (along with its subdirectory and files) from a tar archive, specify the directory name at the end of the tar xvf command as shown below. The following extracts only a specific directory from a large tar file.
$ tar xvf archive_file.tar /path/to/dir/

To extract multiple directories from a tar archive, specify those individual directory names at the end of the tar xvf command as shown below.
$ tar xvf archive_file.tar /path/to/dir1/ /path/to/dir2/

Use the relevant option z or j according to the compression method gzip or bzip2 respectively as shown below.
$ tar xvfz archive_file.tar.gz /path/to/dir/ $ tar xvfj archive_file.tar.bz2 /path/to/dir/

7. Extract group of files from tar, tar.gz, tar.bz2 archives using regular expression
You can specify a regex, to extract files matching a specified pattern. For example, following tar command extracts all the files with pl extension.
$ tar xvf archive_file.tar --wildcards '*.pl'

Options explanation:

wildcards *.pl files with pl extension

8. Adding a file or directory to an existing archive using option -r


You can add additional files to an existing tar archive as shown below. For example, to append a file to *.tar file do the following:
$ tar rvf archive_name.tar newfile

This newfile will be added to the existing archive_name.tar. Adding a directory to the tar is also similar,
$ tar rvf archive_name.tar newdir/

Note: You cannot add file or directory to a compressed archive. If you try to do so, you will get tar: Cannot update compressed archives error as shown below.
$ tar rvfz archive_name.tgz newfile tar: Cannot update compressed archives Try `tar --help' or `tar --usage' for more information.

9. Verify files available in tar using option -W


As part of creating a tar file, you can verify the archive file that got created using the option W as shown below.
$ tar cvfW file_name.tar dir/

If you are planning to remove a directory/file from an archive file or from the file system, you might want to verify the archive file before doing it as shown below.
$ tar tvfW file_name.tar Verify 1/file1 1/file1: Mod time differs 1/file1: Size differs Verify 1/file2 Verify 1/file3

If an output line starts with Verify, and there is no differs line then the file/directory is Ok. If not, you should investigate the issue. Note: for a compressed archive file ( *.tar.gz, *.tar.bz2 ) you cannot do the verification. Finding the difference between an archive and file system can be done even for a compressed archive. It also shows the same output as above excluding the lines with Verify.

Finding the difference between gzip archive file and file system
$ tar dfz file_name.tgz

Finding the difference between bzip2 archive file and file system
$ tar dfj file_name.tar.bz2

10. Estimate the tar archive size


The following command, estimates the tar file size ( in KB ) before you create the tar file.
$ tar -cf - /directory/to/archive/ | wc -c 20480

The following command, estimates the compressed tar file size ( in KB ) before you create the tar.gz, tar.bz2 files.
$ tar -czf - /directory/to/archive/ | wc -c 508 $ tar -cjf - /directory/to/archive/ | wc -c 428

You might also like