- C:-
- C Programming Tutorial (K&R version 4)
- C Programming Tutorial ( About.com)
- Programming in C: A Tutorial
- Introduction to C Programming
- C Programming (Brian Brown)
- C Programming (Steve Holmes)
- C Programming Note (Steve Summit)
- Programming in C (peter Burden)
- C Elements of Style
- Programming in C -- UNIX System Calls and Subroutines Using C ( A D Marshall )
- ANSI C for Programmers on UNIX Systems
- Writing Bug-Free C Code
- A Tutorial On Pointers And Arrays In C
- C Language Reference Manual
- The Function Pointer Tutorials
- Sams Teach Yourself C in 21 Days, 4th Ed.
- The C Library Reference Guide
- Object-Oriented Programming with ANSI C
- Introduction to C and C++ Programming
- C++ :-
- Introductory
- A Beginner's C++
- Programming with Class: A Practical Introduction to Object Oriented Programming with C++
Thinking in C++, by Bruce Eckel, 2nd Edition, Vol. 1 - Thinking in C++, by Bruce Eckel, 2nd Edition, Vol. 2
- An Introduction to C++ and Object Oriented Programming (Ian D Chivers)
- Introduction to Object-Oriented Programming Using C++
- Introduction to C++ Programming
- C++ Programming for Scientists
- About.com :: C++ Tutorial
- An Introduction to C++ Programming (Björn Fahller)
- cplusplus.com :: C++ Language Tutorial
- Coronado Enterprises C++ Tutor, v 2.2
- Teach Yourself C++ in 21 Days
- C++ Annotation
- Objects first
- How to think like a computer scientist using C++
- FunctionX C++ Tutorial
- Intermediate/Advanced
- Scientific C++
- Techniques for Scientific C++
- Available C++ Libraries FAQ
- Template Numerical Toolkit
- Blitz++ :: Object Oriented Scientific Computing
- Standard Template Library
- Coding Standards
- Introductory
Friday, September 5, 2008
c and c++ tutorials
RPM manager
RPM is a recursive acronym for RPM Package Manager (Formerly known as Redhat Package Manager). It is the default package manager in RedHat as well as RedHat based Linux distributions like Mandrake, OpenSuSE, PCLinuxOS and so on [Read about these Linux distributions here ]. It is very powerful and can be used to install, remove, update software, as well as a whole lot of other things in Linux. Basically, RPM can be divided into 3 main areas of functionality.
- Packages - Files that are compressed and contain applications, data and other files.
- Database - A list of installed packages in a system.
- Compilation - Bundling a bunch of files into a package suitable for installation on other systems.
Here are a couple of important RPM commands that are frequently used by Linux users though now a days, they use other tools (such as Yum) which provide automatic dependency checking to achieve the same.
Querying - Know more about a package
You can query the RPM database to know more details about a particular package that is installed in your system. To see if a particular program (say gedit, a text editor) is installed or not, use -q to activate the query mode in RPM.
# rpm -q geditRPM usually responds with the name, version and release of the package installed or, more likely reports that it is not present. To see all the files that are installed for gedit and their full path, use the -l sub parameter with the query mode.
# rpm -q -l geditHere -q is the mode and -l is the submode. Usually you can bundle the mode and sub-mode parameters together as follows:
# rpm -ql geditYou can also try...# rpm -qlv gedit... for a more verbose output.To find, in which package the file /bin/sh is located, try :
# rpm -qf /bin/sh
bash-2.05b-38
...which tells that the file /bin/sh is situated in the package bash-2.05b-38.
Now to get more details about the bash package execute the following command:
# rpm -qi bash...which will give a whole lot of details about the bash package installed in your system.Installing and removing packages
Suppose you want to install a package (say gedit):
# rpm -ivh gedit-2.6.0-4.rpmTo update gedit to a newer version:
# rpm -Uvh gedit-2.8.0-6.rpmThe -U mode means, if this package is not installed, install it; if an older version of this package is installed, upgrade it.
There is a third installation mode, called freshening, represented by -F. This is similar to -U in that it upgrades a package that is installed, but it adds one restriction - it ignores any packages that are not of the same name as a package that is already installed on your system. So if you have a directory containing a bundle of rpms - say security patches - then you can move into that directory containing the security patches in RPM format and execute the command:
# rpm -Fvh *.rpm... which will install only those security patches which are related to the packages that are already installed in your system and will ignore the rest.
To remove an already installed package say gedit, just type:
# rpm -e geditDrawbacks of RPM
RPM has one difficulty, ie it will not install a package if that package depends on another program that is not already installed on your system. This is known as a dependency issue. RedHat provides two utilities called rpmdb-redhat for RedHat enterprise linux and rpmdb-fedora for Fedora Core. Once you install one of these on your system, RPM will automatically begin suggesting dependency resolutions.
Of course, you can force RPM to install a package even without resolving a dependency problem by using the --force and --nodeps parameters to both the installation related modes and the remove mode. They ignore conflicts and dependencies respectively.
Suppose you do not want to install an RPM package but get one or more files in it. You can use a utility called rpm2cpio to convert your RPM package into a cpio package (which is more or less similar to a tarball) then use the command cpio to extract all the files into a directory as follows:
Suppose you do not want to install an RPM package but get one or more files in it. You can use a utility called rpm2cpio to convert your RPM package into a cpio package (which is more or less similar to a tarball) then use the command cpio to extract all the files into a directory as follows:
# rpm2cpio PackageName | cpio -idThis will extract all the files from the RPM package into the current directory. This is only a small subset of the power of RPM. To know more about it try:
# man rpm
proc filesystem
Linux has become really popular as a server operating system mainly due to its security and stability. Infact the system administrators could do system maintanence tasks short of any hardware upgradations without rebooting the machine. That means there is virtually no downtime suffered by a linux server. This is made possible because Linux provides various ways to change the underlying operating system values and settings while keeping the system up and running. Linux contains a virtual filesystem called /proc which can be accessed by the system administrators to achieve the above tasks.
A /proc filesystem is not a real filesystem because it resides only in the computer's memory and does not utilize any space on the hard disk. This filesystem is a map to the running kernel process. The /proc filesystem is mounted in the /proc directory during system initialization and has an entry in the /etc/fstab file.
If you move into the /proc directory, you will find a lot of sub directories and files. Some of these files give information on system hardware, networking settings and activity, memory usage and so on of your computer. And there are some other files in the /proc/sys directory whose values you can manipulate to make changes to the various parameters of the running kernel settings.
Here I will describe the various files and directories residing in /proc that a system administrator could find helpful.
If you list the files under /proc, you will find that all the files have a size of zero - this is because they are not really files and directories in the typical sense. If you want to view the contents of a file in the /proc directory, you use the 'cat' command.
WARNING: Do not use 'cat' on /proc/kcore as this is a special file which is an image of the running kernel's memory at that particular moment - cat'ing this file will leave your terminal unusable.
Some of the key files in the top-level directory are as follows :- /proc/interrupts - View IRQ settings
- /proc/cpuinfo - Information about the system's CPU(s)
- /proc/dma - Direct Memory Access (DMA) settings
- /proc/ioports - I/O settings.
- /proc/meminfo - Information on available memory, free memory, swap, cache memory and buffers. You can also get the same information using the utilities free and vmstat.
- /proc/loadavg - System load average
- /proc/uptime - system uptime and idle time. Can also be obtained using utility uptime.
- /proc/version - Linux kernel version, build host, build date etc. Can also be obtained by executing `uname -a`.
Beneath the top-level /proc directory are a number of important subdirectories containing files with useful information. These include :
- /proc/scsi - Gives information about SCSI devices
- /proc/ide - information about IDE devices
- /proc/net - information about network activity and configuration
- /proc/sys - Kernel configuration parameters. The values in files in this directory are editable by root, which I will further explain below.
- /proc/
- information about process PID.
As explained earlier, this directory holds most kernel configuration parameters and is the one that is designed to be changed while the system is running. Some of the files which are of real use to the system administrators are as follows:
- /proc/sys/fs/file-max
This specifies the maximum number of file handles that can be allocated. If some of your users get an error when trying to open more files stating that the maximum limit of number of open files have been reached, then you need increase the value in this file (default is 4096) to set the problem straight as follows :# echo "10000" > /proc/sys/fs/file-max
- /proc/sys/fs/super-max
This specifies the maximum number of super block handlers. Any filesystem you mount needs to use a super block, so you could possibly run out if you mount a lot of filesystems.
Default setting: 256 - /proc/sys/kernel/acct
This holds three configurable values that control when process accounting takes place based on the amount of free space (as a percentage) on the filesystem that contains the log:
- If free space goes below this percentage value then process accounting stops.
- If free space goes above this percentage value then process accounting starts.
- The frequency (in seconds) at which the other two values will be checked.
Default setting: 2 4 30
These values will stop accounting if there is less than 2 percent free space on the filesystem that contains the log and starts it again if there is 4 or more percent free space. Checks are made every 30 seconds. - /proc/sys/kernel/ctrl-alt-del
This file holds a binary value that controls how the system reacts when it receives the ctrl+alt+delete key combination. The two values represent:
- A zero (0) value means the ctrl+alt+delete is trapped and sent to the init program. This will allow the system to have a graceful shutdown and restart, as if you typed the shutdown command.
- A one (1) value means the ctrl+alt+delete is not trapped and no clean shutdown will be performed, as if you just turned the power off.
- /proc/sys/kernel/domainname
This allows you to configure your network domain name. This has no default value and may or may not already be set. - /proc/sys/kernel/hostname
This allows you to configure your network host name. This has no default value and may or may not already be set. - /proc/sys/net/ipv4/ip_forward
This allows you to turn on/off IP forwarding. If the value in this file is "1" then ip forwarding is turned "on "and if value is "0" then ip forwarding is turned off.
But the /proc/sys modifications are temporary and are not saved at system shutdown (which may be a rare instance as far as servers are concerned). But you can use the "sysctl" command to manage such settings in a static and centralized fashion. It reads the values in the /etc/sysctl.conf file. The sysctl command is called during boot time by the /etc/rc.d/rc.sysinit script. So to make the changes you make in the kernel parameters permanent, just enter it in the /etc/sysctl.conf file and then execute the command :
# sysctl -p... to make the kernel reread the changes from the /etc/sysctl.conf file.
There are two simple rules for converting between files in /proc/sys and variables in sysctl:
- Drop the /proc/sys from the beginning.
- Swap slashes for dots in the filenames.
So /proc/sys/net/ipv4/ip_forward will become net.ipv4.ip_forward
There is an interesting article about the /proc filesystem at Linux Gazette.
Bash shell shortcuts
Bash, which is the default shell in Linux contains a whole lot of key bindings which makes it really easy to use . The most commonly used shortcuts are listed below :
____________CTRL Key Bound_____________
Ctrl + a - Jump to the start of the line
Ctrl + b - Move back a char
Ctrl + c - Terminate the command
Ctrl + d - Delete from under the cursor
Ctrl + e - Jump to the end of the line
Ctrl + f - Move forward a char
Ctrl + k - Delete to EOL
Ctrl + l - Clear the screen
Ctrl + r - Search the history backwards
Ctrl + R - Search the history backwards with multi occurrence
Ctrl + u - Delete backward from cursor
Ctrl + xx - Move between EOL and current cursor position
Ctrl + x @ - Show possible hostname completions
Ctrl + z - Suspend/ Stop the command
____________ALT Key Bound___________
Alt + < - Move to the first line in the history
Alt + > - Move to the last line in the history
Alt + ? - Show current completion list
Alt + * - Insert all possible completions
Alt + / - Attempt to complete filename
Alt + . - Yank last argument to previous command
Alt + b - Move backward
Alt + c - Capitalize the word
Alt + d - Delete word
Alt + f - Move forward
Alt + l - Make word lowercase
Alt + n - Search the history forwards non-incremental
Alt + p - Search the history backwards non-incremental
Alt + r - Recall command
Alt + t - Move words around
Alt + u - Make word uppercase
Alt + back-space - Delete backward from cursor
----------------More Special Keybindings-------------------
Here "2T" means Press TAB twice
$ 2T - All available commands(common)
$ (string)2T - All available commands starting with (string)
$ /2T - Entire directory structure including Hidden one
$ 2T - Only Sub Dirs inside including Hidden one
$ *2T - Only Sub Dirs inside without Hidden one
$ ~2T - All Present Users on system from "/etc/passwd"
$ $2T - All Sys variables
$ @2T - Entries from "/etc/hosts"
$ =2T - Output like ls or dir
Read more!
Vim editor
You select any Linux/Unix OS distribution; from the spartan linux which fits on a floppy to the industry heavy weights like redhat and suse; you are guaranteed to find the vi editor. So it is really worth ones time to learn how to use this powerful but simple editor. Vim is the modern version of the vi editor. Learning to use vim (vi) contains an initial learning curve. But the power it gives the user to accomplish complex text manipulation with just a few keystrokes makes the trouble taken to learn worth it.
Here I will explain a few commonly used commands in Vim. Vim (vi) is an editor with modes of operation. There are three modes of operation in vim. They are as follows :
Command modeThis is the default when you start vi. In command mode, the keys entered are treated as commands, rather than as text input. Most commands are single letters. Case (upper or lower) is significant. Some commands can be combined, or prefixed with qualifiers.
Input ModeInput mode means that what ever you type (except the Escape key) is understood by vi to be the text that you want to enter into the file, and is not a command. There are many ways of entering input mode. But only one way of exiting Input Mode - Which is by typing Escape, which puts you back into the Command mode.
Last Line ModeIn this mode, you are actually entering commands to the ex editor, on which vi is built. You get into the last line mode from the command mode by typing a colon (:) character. The colon, and whatever you type after it, is displayed on the last line of the screen (which is how this mode gets its name). All characters you type after the colon, until the carriage return, are treated as ex commands.
Command ModeCursor Movement Commands
h - j - k - l - These commands move the cursor left - down - up - right in that order.n| - Moves the cursor to the n'th character on the line. If the character position is invalid, vi beeps. Just "|" by itself moves the cursor to the begining of the line.0 - Moves the cursor to the begining of the line.
^ - Moves the cursor to the first non blank character in the line.
$ - Moves the cursor to the end of the line.
fx - (where x is any character) Searches forward for the next occurence of that character from the cursor position, on the current line only.Fx - Works the same as fx but in reverse direction.
[wW],[bB] - Move one word forward and backward respectively.
H - Moves the cursor to the top (highest) line on the screen.
M - Moves the cursor to the middle line on screen
L - Moves the cursor to the lowest line on screen
Ctrl-d - Scrolls down by half page.
Ctrl-u - Scrolls up by half page
Ctrl-f, Ctrl-b - Scroll forward and backward a page.
nG - Where "n" is a number.goes to that line number in the file. Example, 1G goes to the top of the file. 157G to the 157th line and so on.Mx - Where "x" is any single letter, marks the current line with a marker called x. Later you can move back to that line with the command 'x. Note : To go to the exact cursor position of the mark, use ` instead of the forward single quote.`` - (This is a single quote typed twice, not a double quote) acts as a toggle and takes you to the position you were at before. So you can repeatedly switch between two positions in the file.Text Modification Commands
x - Deletes the character under the cursor.
rn - (where "n" is any character) replaces the character under the cursor with the character n.
cw - (change word) puts you into input mode by replacing the word that the current cursor is on.
dw - (delete word) deletes the current word you are on.
dd - (delete line) deletes the current line you are on.
yy - yanks (copies) a line into the buffer.
p - pastes the yanked line at the position of the cursor.
Input Mode
i - Which means insert text before the cursor. This command puts you in Input Mode.
I - Same as above but it starts at the begining of the line.
a - Which means apend text after the cursor. This command puts you in Input Mode.
A - Same as above but starts appending at the end of the current line.
R - Replace characters.Puts you in another kind of input mode (called replace mode) in which what ever you type overwrites whatever is under the cursor. This goes on till you type Esc.o - Which means open mode. Opens a new line below the current line.
O - Opens a new line above the current line.
Last Line Mode Commands
:w - Saves the file in the same name that you opened it with.
:w filename - Similar to "save as" command. In vim, you can also use the :sav filename command to accomplish the same function.
:n,m w filename - This saves the contents of line numbers n to m to the given filename. Use $ instead of m to refer to the last line number without knowing what its value is.
:e filename - This is to start editing another file instead of the current one. Once you have used the e command, you can toggle back and forth between the two files by the command :e#. If you have made a lot of changes (and not saved), and now want to discard all of them, type :e!.
:r filename - The read command, reads in the file and inserts its contents below the current line.
What I have explained above is only a tiny sample of commands which a beginner in vi (vim) can start using. You can rest assured that there are many many more . If you want to learn more advanced commands, the best way to do is to read the Vim manual which gets installed along with the editor. Just type
:help in the command mode and start reading the manual. Three excellent resources on Vim that I have come across on the web which are worth reading are Seven habits of effective text editing by Bram Moolenaar who is the developer of vim , Efficient Editing With vim , and Best of Vim tips .Routers,gateways and NAT in linux
A router is a device that directs network traffic destined for an entirely different network in the right direction. For example, suppose your network is having the IP address range of 192.168.1.0/16 and you also have a different network which has a network addresses in range 192.168.2.0/16 . Note that these are 'Class C' network addresses which are subnetted. So for your computer ( on the network 192.168.1.0/16 ) to directly communicate between a computer in the network 192.168.2.0/16, you need a intermediary to direct the traffic to the destination network. This is achieved by a router.
Configuring Linux as a router
Linux can be effectively configured to act as a router between two networks. To activate routing functionality , you enable IP forwarding in Linux. This is how you do this:
# echo "1" > /proc/sys/net/ipv4/ip_forward
Now you have enabled IP forwarding in Linux. Now make this change persistent across reboots by editing the file /etc/sysctl.conf and entering the following line:
#FILE : /etc/sysctl.conf
...
net.ipv4.ip_forward = 1
...
Optionally, after editing the above file, you may execute the command :
# sysctl -p
Note: For your linux machine to act as a router, you need two ethernet cards in your machine or you can also configure a single ethernet card to have multiple IP addresses.
What is a gateway?
Any device which acts as the path to or from your network to another network or the internet is considered to be a gateway. Let me explain this with an example: Suppose your computer, machine_B has an address 192.168.0.5 with default netmask. And another computer (machine_A) with an IP address 192.168.0.1 in your network is connected to the internet using a USB cable modem. Now if you want machine_B to send or recieve data destined for an outside network a.k.a internet, it has to direct it to machine_A first which forwards it to the internet. So machine_A acts as the gateway to the internet. Each machine needs a default gateway to reach machines outside the local network. You can set the gateway in machine_B to point to machine_A as follows:
# route add default gw machine_A
Or if DNS is not configured...
# route add default gw 192.168.0.1
Now you can check if the default gateway is set on machine_B as follows:
# route -n
As you can see in the image above, the machine_B has the default gateway set to 192.168.0.1 . And the default gateway has the flag set as UG - 'G' means Gateway and 'U' means the network is UP.Note: Additional routes can be set using route command. To make the changes persistent across reboots, you may edit the /etc/sysconfig/static-routes file to show the configured route.
What is NAT ?
Network Address Translation (NAT) is a capability of linux kernel where the source or destination address / port of the packet is altered while in transit.
This is used in situations where multiple machines need to access the internet with only one official IP address available. A common name for this is IP masquerading. With masquerading, your router acts as a OSI layer 3 or layer 4 proxy. In this case, Linux keeps track of the packet(s) journey so that during transmission and recipt of data, the content of the session remains intact. You can easily implement NAT on your gateway machine or router by using Iptables, which I will explain in another post.
Related Posts :
How to install network card in Linux
How to assign an IP address
Setting up multiple IP addresses on a single NIC
Locate files using find command
Find is a versatile tool which can be used to locate files and directories satisfying different user criteria. But the sheer number of options for this command line tool makes it at the same time both powerful and encumbering for the user. Here I will list a few combinations which one can use to get useful results using find command.
Find all HTML files starting with letter 'a' in your current directory (Case sensitive)
$ find . -name a\*.htmlSame as above but case insensitive search.
$ find . -iname a\*.htmlFind files which are larger than 5 MB in size.
$ find . -size +5000k -type f Here the '+' in '+5000k' indicates greater than and k is kilobytes. And the dot '.' indicates the current directory. The -type option can take any of the following values:
Find all empty files in your directory
f - file
d - directory
l - symbolic link
c - character
p - named pipe (FIFO)
s - socket
b - block device
$ find . -size 0c -type f... Which is all files with 0 bytes size. The option -size can take the following:
c - bytes
w - 2 byte words
k - kilo bytes
b - 512 byte blocks
Note: The above command can also take the -empty parameter.
Find is very powerful in that you can combine it with other commands. For example, to find all empty files in the current directory and delete them, do the following:
$ find . -empty -maxdepth 1 -exec rm {} \;To search for a html file having the text 'Web sites' in it, you can combine find with grep as follows:
$ find . -type f -iname \*.html -exec grep -s "Web sites" {} \;... the -s option in grep suppresses errors about non-existent or unreadable files. And {} is a placeholder for the files found. The semicolon ';' is escaped using backslash so as not to be interpreted by bash shell.
Note: You can use the -exec option to combine any command in Linux with the find command. Some of the useful things you can do with it are as follows:
Compress log files on an individual basis
$ find /var -iname \*.log -exec bzip {} \;Find all files which belong to user lal and change its ownership to ravi
# find / -user lal -exec chown ravi {} \;Note: You can also use xargs command instead of the -exec option as follows:
$ find /var -iname \*.log | xargs bzip -Find all files which do not belong to any user:
$ find . -nouserFind files which have permissions rwx for user and rw for group and others :
$ find . -perm 766... and then list them.
$ find . -perm 766 -exec ls -l {} \;Find all directories with name music_files
$ find . -type d -iname \*music_files\*Suppose you want to find files of size between 700k and 1000k, do the following:
$ find . \( -size +700k -and -size -1000k \)And how about getting a formatted output of the above command with the size of each file listed ?
$ find . \( -size +700k -and -size -1000k \) -exec du -Hs {} \; 2>/dev/null... here, the '2>/dev/null' means all the error messages are discarded or suppressed.
You can also limit your search by file system type. For example, to restrict search to files residing only in the NTFS and VFAT filesystem, do the following:
$ find / -maxdepth 2 \( -fstype vfat -or -fstype ntfs \) 2> /dev/nullThese are the most common uses of the find command. You can see additional uses by reading the find manual.
guide to bash shell scripting
First let me clarify that this is not going to be a detailed study of shell scripting, but as the name of the post indicates, it will be a quick reference to the syntax used in scripting for the bash shell. So if you are expecting the former, then you should buy yourself a good book on shell scripting . ;-) So let's move on to the guide. Start your stop watch now.
-- Start of The 10 secs Guide to Bash Scripting --
Common environment variablesPATH - Sets the search path for any executable command. Similar to the PATH variable in MSDOS.
HOME - Home directory of the user.MAIL - Contains the path to the location where mail addressed to the user is stored.
IFS - Contains a string of characters which are used as word seperators in the command line. The string normally consists of the space, tab and the newline characters. To see them you will have to do an octal dump as follows:
$ echo $IFS | od -bcPS1 and PS2 - Primary and secondary prompts in bash. PS1 is set to $ by default and PS2 is set to '>' . To see the secondary prompt, just run the command :
$ ls |... and press enter.USER - User login name.
TERM - indicates the terminal type being used. This should be set correctly for editors like vi to work correctly.
SHELL - Determines the type of shell that the user sees on logging in.Note: To see what are the values held by the above environment variables, just do an echo of the name of the variable preceeded with a $. For example, if I do the following:
$ echo $USER
ravi... I get the value stored in the environment variable USER.Some bash shell scripting rules
1) The first line in your script must be
#!/bin/bash ... that is a # (Hash) followed by a ! (ban) followed by the path of the shell. This line lets the environment know the file is a shell script and the location of the shell.
2) Before executing your script, you should make the script executable. You do it by using the following command:
$ chmod ugo+x your_shell_script.sh 3) The name of your shell script must end with a .sh . This lets the user know that the file is a shell script. This is not compulsary but is the norm.
Conditional statements
The 'if' Statement - evaluates a condition which accompanies its command line. Those words marked in blue are compulsory. But those marked in red are optional.
syntax:if condition_is_true
then
execute commands
else
execute commands
fi if condition also permits multiway branching. That is you can evaluate more conditions if the previous condition fails.
if condition_is_true
then
execute commands
elif another_condition_is_true
then
execute commands
else
execute commands
fiExample :if grep "linuxhelp" thisfile.html
then
echo "Found the word in the file"
else
echo "Sorry no luck!"
fiif's companion - testtest is an internal feature of the shell. test evaluates the condition placed on its right, and returns either a true or false exit status. For this purpose, test uses certain operators to evaluate the condition. They are as follows:
Relational operators
-eq Equal to
-lt Less than
-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less than or equal to File related tests-f file True if file exists and is a regular file
-r file True if file exists and is readable
-w file True if file exists and is writable
-x file True if file exists and is executable
-d file True if file exists and is a directory
-s file True if file exists and has a size greater
than zero.String tests-n str True if string str is not a null string
-z str True if string str is a null string
str1 == str2 True if both strings are equal
str1 != str2 True if both strings are unequal
str True if string str is assigned a value
and is not null.Test also permits the checking of more than one expression in the same line.-a Performs the AND function
-o Performs the OR functionExample:test $d -eq 25 ; echo $d... which means, if the value in the variable d is equal to 25, print the value.test $s -lt 50; do_somethingif [ $d -eq 25 ]
then
echo $d
fi In the above example, I have used square brackets instead of the keyword test - which is another way of doing the same thing.
if [ $str1 == $str2 ]
then
do something
fi
if [ -n "$str1" -a -n "$str2" ]
then
echo 'Both $str1 and $str2 are not null'
fi
... above, I have checked if both strings are not null then execute the echo command.Things to remember while using test
If you are using square brackets [] instead of test, then care should be taken to insert a space after the [ and before the ].
Note: test is confined to integer values only. Decimal values are simply truncated.Do not use wildcards for testing string equality - they are expanded by the shell to match the files in your directory rather than the string.
Case statement
Case statement is the second conditional offered by the shell.
Syntax:
case expression in
pattern1) execute commands ;;
pattern2) execute commands ;;
...
esac The keywords here are in, case and esac. The ';;' is used as option terminators. The construct also uses ')' to delimit the pattern from the action.
Example:
...
echo "Enter your option : "
read i;
case $i in
1) ls -l ;;
2) ps -aux ;;
3) date ;;
4) who ;;
5) exit
esac
Note: The last case option need not have ;; but you can provide them if you want.Here is another example:
case `date |cut -d" " -f1` in
Mon) commands ;;
Tue) commands ;;
Wed) commands ;;
...
esac
Case can also match more than one pattern with each option.You can also use shell wild-cards for matching patterns.
...
echo "Do you wish to continue? (y/n)"
read ans
case $ans in
Y|y) ;;
[Yy][Ee][Ss]) ;;
N|n) exit ;;
[Nn][Oo]) exit ;;
*) echo "Invalid command"
esac
In the above case, if you enter YeS, YES,yEs and any of its combinations, it will be matched.
This brings us to the end of conditional statements.
Looping Statements
while loop
Syntax :
while condition_is_true
do
execute commands
done
Example:while [ $num -gt 100 ]
do
sleep 5
done
while :
do
execute some commands
done
The above code implements a infinite loop. You could also write 'while true' instead of 'while :' .
Here I would like to introduce two keywords with respect to looping conditionals. They are break and continue.
break - This keyword causes control to break out of the loop.continue - This keyword will suspend the execution of all statements following it and switches control to the top of the loop for the next iteration.
until loop
Until complements while construct in the sense that the loop body here is executed repeatedly as long as the condition remains false.
Syntax:until false
do
execute commands
done
Example:...
until [ -r myfile ]
do
sleep 5
done
The above code is executed repeatedly until the file myfile can be read.for loop
Syntax :
for variable in list
do
execute commands
done
Example:...
for x in 1 2 3 4 5
do
echo "The value of x is $x";
done
Here the list contains 5 numbers 1 to 5. Here is another example:
for var in $PATH $MAIL $HOME
do
echo $var
done
Suppose you have a directory full of java files and you want to compile those. You can write a script like this:
...
for file in *.java
do
javac $file
done
Note: You can use wildcard expressions in your scripts.A few special symbols and their meanings w.r.t shell scripts
$* - This denotes all the parameters passed to the script
at the time of its execution. Which includes $1, $2
and so on.
$0 - Name of the shell script being executed.
$# - Number of arguments specified in the command line.
$? - Exit status of the last command.
The above symbols are known as positional parameters. Let me explain the positional parameters with the aid of an example. Suppose I have a shell script called my_script.sh . Now I execute this script in the command line as follows :
$ ./my_script.sh linux is a robust OS
... as you can see above, I have passed 5 parameters to the script. In this scenario, the values of the positional parameters are as follows:
$* - will contain the values 'linux','is','a','robust','OS'.$0 - will contain the value my_script.sh - the name of the script being
executed.
$# - contains the value 5 - the total number of parameters.
$$ - contains the process ID of the current shell. You can use this parameter while giving unique names to any temporary files that you create at the time of execution of the shell.
$1 - contains the value 'linux'
$2 - contains the value 'is'
... and so on.
The set and shift statements
set - Lets you associate values with these positional parameters .
For example, try this:
$ set `date`
$ echo $1
$ echo $*
$ echo $#
$ echo $2
shift - transfers the contents of a positional parameter to its immediate lower numbered one. This goes on as many times it is called.
Example :
$ set `date`
$ echo $1 $2 $3
$ shift
$ echo $1 $2 $3
$ shift
$ echo $1 $2 $3
To see the process Id of the current shell, try this:$ echo $$
2667
Validate that it is the same value by executing the following command:$ ps -f |grep bashread statementMake your shell script interactive. read will let the user enter values while the script is being executed. When a program encounters the read statement, the program pauses at that point. Input entered through the keyboard id read into the variables following read, and the program execution continues.
Eg:#!/bin/sh
echo "Enter your name : "
read name
echo "Hello $name , Have a nice day."
Exit status of the last commandEvery command returns a value after execution. This value is called the exit status or return value of the command. A command is said to be true if it executes successfully, and false if it fails. This can be checked in the script using the $? positional parameter.
Here I have given a concise introduction to the art of bash shell scripting in Linux. But there is more to shell scripting than what I have covered. For one, there are different kinds of shells, bash shell being only one of them. And each shell has a small variation in its syntax. Like the C shell for example, which uses a syntax close to the C language for scripting. But what I have covered above applys to all the shells.
-- End of The 10 secs Guide to Bash Scripting --
Now check how much time you have taken to cover this much.What? You say you have taken more than 10 secs to read the guide ? Then please enter a comment explaining your reasons for taking so much time and I will send you a free gift as compensation for the extra time you spent here.
But if you have taken less than 10 secs to read through the guide, please enter a comment explaining how you accomplished this extraordinary feat. And I will send you a free gift too.
find the speed of ethernet card in linux
For logging on to the net or for attaching as a node on a LAN, your computer needs a network card. The network card forms the interface between your computer and the network. There are different kinds of network cards available in the market depending on its speed and other features. Here is a tip to find out the characteristics of your network card.
If you want to find what type of network card is used, its speed, on which IRQ it is listed, and the chip type used, you use the following command :
# dmesg |grep eth0 Here eth0 is the first network card. If you have additional cards, it will be named eth1, eth2 and so on. And here is the output of the above command :
divert: allocating divert_blk for eth0
eth0: RealTek RTL8139 at 0xd800, 00:80:48:34:c2:84, IRQ 9
eth0: Identified 8139 chip type 'RTL-8100B/8139D'
divert: freeing divert_blk for eth0
divert: allocating divert_blk for eth0
eth0: RealTek RTL8139 at 0xd800, 00:90:44:34:a5:33, IRQ 9
eth0: Identified 8139 chip type 'RTL-8100B/8139D'
eth0: link up, 100Mbps, full-duplex, lpa 0x41E1
eth0: no IPv6 routers present
...
The important things to note here are those highlighted in colour. As you can see from the above listing, my ethernet card is a RealTek RTL8139 chipset based card on IRQ 9 (Interrupt Request). Its speed is 100 Mbps and is a full-duplex card. And the link is up.
As is the philosophy of Linux, there is more than one way of finding the same information. Linux also comes with a cute sounding tool called mii-tool which can also be used to get the same information about your network card.
# mii-tool -v eth0eth0: negotiated 100baseTx-FD, link ok
product info: vendor 00:00:00, model 0 rev 0
basic mode: autonegotiation enabled
basic status: autonegotiation complete, link ok
capabilities: 100baseTx-FD 100baseTx-HD 10baseT-FD
10baseT-HD
...
Here -v is verbose mode. From the above listed output, one can see that the ethernet card is working as a 100baseTX, FD (Full Duplex) card which can work in the following modes :
- 100 Mbps Speed (Full duplex or half duplex ) or
- 10 Mbps speed (Full duplex or half duplex).
And it uses autonegotiation to bring up the link. You can call the above device as a 10/100 NIC.
Another tool which also does the same thing is ethtool. Try the following command on your machine to see the output.
# ethtool eth0
Settings for eth0:
Supported ports: [ TP MII ]
Supported link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
Supports auto-negotiation: Yes
Advertised link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
Advertised auto-negotiation: Yes
Speed: 100Mb/s
Duplex: Full
Port: MII
PHYAD: 32
Transceiver: internal
Auto-negotiation: on
Supports Wake-on: pumbg
Wake-on: p
Current message level: 0x00000007 (7)
Link detected: yes
Here full duplex, half duplex and auto-negotiation have the following meanings.Full Duplex - Logic that enables concurrent sending and receiving. This is usually desirable and enabled when your computer is connected to a switch.
Half Duplex - This logic requires a card to only send or receive at a single point of time. When your machine is connected to a Hub, it auto-negotiates itself and uses half duplex to avoid collisions.
Auto-negotiation - This is the process of deciding whether to work in full duplex mode or half duplex mode. An ethernet card supporting autonegotiation will decide for itself which mode is the optimal one depending on the network it is attached to.
mount your files in linux
In Linux, if you want to access a filesystem be it a CDROM, a partition or a different drive including zip, floppy, usb keys and so on, you have to mount the filesystem first prior to start using it. In most cases, the system will do it for you. But sometimes you have to do it yourselves. This you do by using the 'mount' command. Here I will explain different things you can achieve by using this very important and useful command.
Check which filesystems are mounted
Just enter the command:
$ mount...to see all the filesystems that are mounted on your machine.Re-mount a drive as read-only
This is useful if you want to take a backup of a filesystem in a production server. Once you have taken the backup, you can remount the filesystem as read-write. For example, if I want to remount the already mounted partition /dev/hda2 as read-only, I enter the following mount command:
# mount -o remount,ro /dev/hda2 /mnt/C/ ... so that no one can write to the partition while the backup is going on. Once the backup is finished, I can remount it again as read-write:
# mount -o remount,rw /dev/hda2 /mnt/C/ro - ReadOnlyrw - ReadWrite
You will find the above command useful in a situation in which your system gets corrupt. And when you boot into single user mode, the filesystem is mounted read-only. In which case, you have to remount it as read-write (see the above command) inorder to make changes to the configuration files.
Mounting a ISO image file to view its contents
If you have downloaded an ISO image (perhaps a Linux distribution) from the net and you want to see the contents of the file, there is an easy way of achieving it in Linux. You just mount it using the loopback device as follows:
# mount -t iso9660 -o loop,ro knoppix-4.0.iso /mnt/iso This is desirable in a situation where, you have downloaded a Linux ISO on to your harddisk. But your computer's BIOS does not support booting from the CD Drive. In which case, you have to create a boot disk (floppy) so that you can start the installation by booting from the floppy. Most Linux ISO's contain a floppy bootdisk image which you can copy to your floppy.
Move a already mounted filesystem to another location
I have already mounted a FAT32 partition in the '/mnt/D/' location. Now if I want to delink it from the current location and make it available at another location, I use the --move flag with the mount command as follows:
# mount --move /mnt/D/ /mnt/newLocation/ Now all the files on my FAT32 partition have been moved from /mnt/D/ to the /mnt/newlocation/. The files have not been actually moved but has been decoupled from /mnt/D/ mount point and linked at /mnt/newLocation/ .
Mount a filesystem simultaneously at two different places
I can use the --bind or --rbind option to mount an already mounted, part of file hierarchy or an entire filesystem to another location with different rights.
For example, I have a subdirectory called 'softwares' in the read-only mount point /mnt/D/ , which I want to make accessible to other users for writing data. I can achieve this by using the --bind command as follows:
# mount -o rw --bind /mnt/D/softwares /mnt/backup Now only the subdirectory 'softwares/' is accessible as read-write in the location /mnt/backup .
If you ask me, mount is a very important command in the Linux toolbox. Because, if there was no mount, Linux would not have been the same OS that it is now. The mount command has lots of other options. You may read the man page of mount to know more about it.
Subscribe to:
Posts (Atom)
