Thursday, August 6, 2009

linux network commands

The network commands chapter explains various tools which can be useful when networking with other computers both within the network and accross the internet, obtaining more information about other computers. This chapter also includes information on tools for network configuration, file transfer and working with remote machines.

netstat

Displays contents of /proc/net files. It works with the Linux Network Subsystem, it will tell you what the status of ports are ie. open, closed, waiting, masquerade connections. It will also display various other things. It has many different options.
tcpdump

This is a sniffer, a program that captures packets off a network interface and interprets them for you. It understands all basic internet protocols, and can be used to save entire packets for later inspection.
ping

The ping command (named after the sound of an active sonar system) sends echo requests to the host you specify on the command line, and lists the responses received their round trip time.

You simply use ping as:

ping ip_or_host_name

Note to stop ping (otherwise it goes forever) use CTRL-C (break).
Note Please note


Using ping/smbmount/ssh or other UNIX system programs with a computer name rather than IP address will only work if you have the computer listed in your /etc/hosts file. Here is an example:

192.168.1.100 new

This line says that their is a computer called “new” with IP address 192.168.1.100. Now that it exists in the /etc/hosts file I don't have to type the IP address anymore, just the name “new”.
hostname

Tells the user the host name of the computer they are logged into. Note: may be called host.
traceroute

traceroute will show the route of a packet. It attempts to list the series of hosts through which your packets travel on their way to a given destination. Also have a look at xtraceroute (one of several graphical equivalents of this program).

Command syntax:

traceroute machine_name_or_ip

tracepath

tracepath performs a very simlar function to traceroute the main difference is that tracepath doesn't take complicated options.

Command syntax:

tracepath machine_name_or_ip

findsmb

findsmb is used to list info about machines that respond to SMB name queries (for example windows based machines sharing their hard disk's).

Command syntax:

findsmb

This would find all machines possible, you may need to specify a particular subnet to query those machines only...
nmap

“ network exploration tool and security scanner”. nmap is a very advanced network tool used to query machines (local or remote) as to whether they are up and what ports are open on these machines.

A simple usage example:

nmap machine_name

This would query your own machine as to what ports it keeps open. nmap is a very powerful tool, documentation is available on the nmap site as well as the information in the manual page.

Reset and Change Windows NT/2000 Administrator in Linux

Reset and Change Windows NT/2000 Administrator or User Password with chntpw in Linux

Windows NT, Windows 2000 and Windows XP users who have forgotten the administrator account password has many ways to hack, crack, recover or reset the administrator password. Another way to break into a Windows PC which locks with forgotten or unknown password is to use chntpw, a Linux based program to change and reset the password of a Windows administrator account.

Chntpw is a program designed to overwrite and set Windows NT or Windows 2000 SAM password of any user that has a valid (local) account by modifying the encrypted password in the registry’s SAM file. User of chntpw does not need to know the old password to set a new password. Actually, chntpw is now available in the form of bootdisk or LiveCD which includes necessary stuff to access NTFS partitions and scripts to glue the whole thing together.

Chntpw works on NT system which is offline (turned off), and can only be used on local machine and cannot be used on a remote machine. However, chntpw can be installed on a Linux system such as Ubuntu, and then used to recover by resetting Windows user account password by mounting the Windows drive, connected via physical IDE/SATA/SCSI interface or USB portable disk.

Chntpw can be installed using aptitude for user using Debian based system,

It is pretty easy to use and can be found and installed using aptitude if your using debian based system, or can be downloaded and installed in Ubuntu with a simple “sudo apt-get install chntpw” command. Chntpw is likely to be contained in other distributions package manager too, or the source code can be downloaded from http://home.eunet.no/~pnordahl/ntpasswd/editor.html.

Chntpw Usage Guide

1. Mount the Windows NTFS, FAT or FAT32 partition to the Linux system, allowing read and write access support.
2. Locate the SAM file for Windows 2000, Windows NT or Windows XP, which is normally located at the either \Windows\System32\config or \Winnt\System32\config folder. Change directory to inside the folder, there are a number of files such as SAM, SYSTEM and SECURITY.

Inside the folder, issue the following command to automatically change the administrator password:

chntpw SAM

Issue the following command (replace USERNAME with actual user name on the computer) to change the password for a normal restricted user account:

chntpw -u USERNAME SAM

Tip: To list all the users in the SAM file, use the chntpw -l SAM command.
3. Chntpw will display some information on screen, and then prompt for new password to reset the existing password. Enter a new password for the administrator or user account.

Tip: To reset the password to blank (no) password, enter * (asterisk).
4. Unmount the drive, and then restart the Windows computer. The password for the administrator or user account reseted should be changed accordingly.

There are other options for chntpw, which can be displayed with the following command:

chntpw -h

# chntpw help and usage

chntpw version 0.99.3 040818, (c) Petter N Hagen
chntpw: change password of a user in a NT SAM file, or invoke registry editor.
chntpw [OPTIONS] [systemfile] [securityfile] [otherreghive] [...]
-h This message
-u Username to change, Administrator is default
-l list all users in SAM file
-i Interactive. List users (as -l) then ask for username to change
-e Registry editor. Now with full write support!
-d Enter buffer debugger instead (hex editor),
-t Trace. Show hexdump of structs/segments. (deprecated debug function)
-v Be a little more verbose (for debuging)
-L Write names of changed files to /tmp/changed
-N No allocation mode. Only (old style) same length overwrites possible
See readme file on how to extract/read/write the NT's SAM file
if it's on an NTFS partition!
Source/binary freely distributable. See README/COPYING for details
NOTE: This program is somewhat hackish! You are on your own!

Wednesday, August 5, 2009

Installing using an RPM file

f you have an rpm file for a package you wish to install, and if you cannot find a .deb debian package in any of the Ubuntu repositories or elsewhere, you can use the alien package converter application to install the .rpm file

Alien is a program that converts between the rpm, dpkg, stampede slp, and slackware tgz file formats. If you want to use a package from another distribution than the one you have installed on your system, you can use alien to convert it to your preferred package format and install it

Despite the large version number, alien is still (and will probably always be) rather experimental software. It has been used by many people for many years, but there are still many bugs and limitations.

Alien should not be used to replace important system packages, like sysvinit, shared libraries, or other things that are essential for the functioning of your system. Many of these packages are set up differently by Debian and Red Hat, and packages from the different distributions cannot be used interchangably. In general, if you can’t uninstall the package without breaking your system, don’t try to replace it with an alien version.
Installing Alien

You can install alien itself from the Ubuntu Universe repository by adding the repository to your list of sources and doing:

$sudo apt-get update
$sudo apt-get install alien
Installing the .rpm file

To install the .rpm file, you first need to convert it to a .deb file which can be installed on Ubuntu.
I assume that you downloaded the package to your Desktop (~/Desktop is the directory)
You can convert the .rpm to a .deb by using the following commands.
$cd ~/Desktop
-This will change the directory to your desktop, where you have the .rpm file.

$sudo alien -k name-of-rpm-file.rpm
- This will convert the .rpm to a .deb.
- The “-k” will keep the version number. Otherwise alien adds a “1″ to the version number.
- Tip: Use Smart Tab Completion to avoid mistyping the file names :)

$sudo dpkg -i name-of-deb-file.deb
- This will install the .deb package

Try reading the alien manpage for more details on how to convert other kinds of packages and the options available.

Monday, August 3, 2009

Symbolic Link

What are they?

Symbolic links are like shortcuts or references to the actual file or directory. Most of the time these links are transparent when working with them through other programs. For example you could have a link to a directory to one hard drive inside a directory that lies on a different hard drive and an application will still treat it the same.

Symbolic links are used all the time to link libraries and make sure files are in consistent places without moving or copying the original. Links are often used to “store” multiple copies of the same file in different places but still reference to one file.

Creating a Symbolic Link

To create a symbolic link in Linux we use this syntax:

ln -s /path/to/original/ /path/to/linkName

What happens if I edit the link? Any modifications to the linked file will be changed on the original file.
What happens if I delete the link? If you delete the link the original file is unchanged. It will still exist.
What happens if I delete the original file but not the link? The link will remain but will point to a file that does not exist. This is called an orphaned or dangling link.

Creating a Hard Link

You can create a hard link like so:

ln /path/to/original.file /path/to/link.file

The Difference Between Soft and Hard Links

Hard links

  • Only link to a file not a directory
  • Can not reference a file on a different disk/volume
  • Links will reference a file even if it is moved
  • Links reference inode/physical locations on the disk

Symbolic (soft) links

  • Can link to directories
  • Can reference a file/folder on a different hard disk/volume
  • Links remain if the original file is deleted
  • Links will NOT reference the file anymore if it is moved
  • Links reference abstract filenames/directories and NOT physical locations. They are given their own inode

Practice Makes Perfect

To really grasp the concept of symbolic links lets give it a shot.

Go into the tmp directory:

cd /tmp

Make a directory

mkdir original

Copy over the host.conf file or any file to test with.

cd original
cp /etc/host.conf .

List the contents and take note of the inode (first column)

ls -ila

Create a symbolic link to host.conf called linkhost.conf

ln -s host.conf linkhost.conf

Now do list out the inodes

ln -ila

Notice how the inode for the link is different.

Now create a hard link to the same file

ln host.conf hardhost.conf

Now list the inoes one more time

ln -ila

Notice how the inode numbers are exactly the same for the hard link and the actual file.

Lets try some file operations now

Open up linkhost.conf and edit it and save it

Now look in host.conf and notice that the changes were made

Lets move host.conf now and see if it causes any problems

mv host.conf ../

Uh oh, now when we list the directory our link turned red lets see what is in side it

cat linkhost.conf
cat: linkhost.conf: No such file or directory

It looks like our symbolic link is now broken as it linked to a file name and not the inode. What about our hard link?

cat hardhost.conf

Looks like our hard link still works even though we moved the original file. This is because the hard link was linked to the inode the physical reference on the hard drive where the file resides. The soft link (symbolic link) on the other hand was linked to the abstract file name and was broken the moment we moved the file.

This leads to an interesting question. What happens if I delete a hard link? Even though the hard link is referenced to the physical location of the file on the hard drive though an inode, removing a hard link will not delete the original file.

Symbolic links will remain intact but will point to a non existent file.

Introduction to fstab

The fstab is one of the first configuration files new Linux users get their hands on. Fstab stands for File System Table. It is basically a config file that will tell your computer which devices (or virtual devices) to use on boot.

The Fstab

In almost all distributions the fstab file is located in ‘/etc/fstab/‘. You can open it up with your favorite editor:

vim /etc/fstab

Syntax

<file system> <dir> <type> <options> <dump> <pass>

File System

The first one, file system revers the block device:

  • /dev/cdrom

  • /dev/sda1
  • /dev/dvd
  • UUID=8af8255331ab
  • LABEL=

Dir

This will be the directory where the device will be mounted to. In other words this will be the directory you will need to access in order to view the contents of the device. The general rule of thumb is that physical internal mounts are stored in /mnt and removable media is stored in /media.

Typical directories

  • /mnt/someDrive
  • /media/cdrom
  • /media/dvd
  • /media/someNFS

Type

The type specifies which type of file system you are trying to mount.

Common types are:

  • ext3 – Linux FS
  • ext4 – Version 4 of ext
  • auto – Usually used for CD-ROM mounts
  • ntfs-3g – NTFS (Windows)
  • cifs – Windows file sharing
  • nfs – Linux file sharing

To see all the file systems you have currently supported, do:

cat /proc/filesystems

Options

This section is where you specify file system specific options.

Dump

This field is used for file systems that use the dump command. A zero here will mean that the file system does not need to be “dumped”. Dump is a utility that will do a backup on the file system. Usually this value is set to zero.

Pass

Pass is the fsck (file system check) order. There are only 3 valid options here.

  • 0 – do not check.
  • 1 – check this partition first.
  • 2 – check this partition(s) next

Usually you set your root partition to be checked first with ‘1‘ and set all other partitions to ‘2‘.

If you want to disable file system checking all together on the device use a ‘0‘. This is commonly done on network shares and remote file systems.

Remount Everything in Fstab

It is common to want to update the system after you have made changes to the fstab config without having to reboot the computer.

To remount everything in fstab without restarting do:

sudo mount -a

Mount by UUID

You can run into problems when mounting removable devices using the ‘/dev/sdb1‘ style. This style of pointing to devices depends on the order in which they are detected in boot which can change depending on if you add or change a hard drive or plug multiple USB devices in. For this reason I have been mounting all of my devices with the UUID instead.

Using the UUID of the hard drive we can mount the same drive no matter which order it comes up in boot or when it is detected. The UUID is a unique identifier for that particular drive. Linux will make no mistake when it comes to mounting file systems that are mapped by their UUID in fstab.

For example:

UUID=18EC910AEAEA90D084 /mnt/someDrive ntfs-3g defaults,user 0 1

This drive will always be mounted at the mount point ‘/mnt/someDrive‘ even if we add or remove one of the other drives in the system.

To get the UUID of a drive first find traditional unix stlye map with:

sudo fdisk -l

This will give you a list of drives with some good identifying material, such as file system type and disk size. Look for the section that starts with ‘/dev/‘ and remember what it says. For example mine says, ‘/dev/sdd1‘.

Then do:

ls -l /dev/disk/by-uuid

This will print out all the UUIDs for each device.

Mounting NFS Shares

Here is an example of mounting an NFS share.

192.168.1.X:/media/sharename /media/sharename nfs rsize=8192,wsize=8192 0 0

Mounting Samba (Windows) Shares

Many systems are in a network with other operating systems. In order to communicate with Windows shares you will need to use cifs or smbfs.

//192.168.1.X/sharename /media/sharename cifs rw,user,username=username,password=password 0 0

Inevitably you are going to run across a Windows share that has a space in its name. Be sure to read: Mounting a Samba Share that has Spaces to find out how to work around the problem.

Mounting NTFS Shares

In order to mount NTFS (Windows) drives in Linux you will need to get the ntfs-3g driver. Which is the third generation of NTFS drivers. Ntfs-3g supports reading and writing to NTFS drives where older NTFS drivers only support reading.

UUID=18EC910AEAEA90D084 /mnt/someDrive ntfs-3g defaults,user 0 1

You might also want to check out Setting up sshfs. To mount directories over the secure protocol, SSH.

Mounting ntfs file system

1) sudo apt-get install ntfs-3g

Installs ntfs-3g library
2) sudo fdisk -l

Shows all the disk drives
3) sudo mkdir /media/windowsC

Create a directory for mounting your NTFS file system

Ubuntu logo
4) sudo cp /etc/fstab /etc/fstab.bak

Take a backup of old conf file

5) gksudo gedit /etc/fstab

Edit the configuration file

6) /dev/sda2 /media/windowsC ntfs-3g defaults,locale=en_US.utf8 0 0

Add the above line to the end of that file. (Here sda2 is the ntfs partition, getting from fdisk -l )


It is common to want to update the system after you have made changes to the fstab config without having to reboot the computer.

To remount everything in fstab without restarting do:
sudo mount -a








This
bash script tutorial assumes no previous knowledge of bash scripting.As
you will soon discover in this quick comprehensive bash scripting
guide, learning the bash shell scripting is very easy task. Lets begin
this bash scripting tutorial with a simple "Hello World" script. Let's
start with Learning the bash Shell: Unix Shell Programming


1. Hello World Bash
Shell Script






First you need to find out where is your bash interpreter
located. Enter the following into your command line:



$ which bash 


bash interpreter location: /bin/bash


Open up you favorite text editor and a create file called
hello_world.sh. Insert the following lines to a file:


NOTE:Every bash shell script in this tutorial starts with shebang:"#!"
which is not read as a comment. First line is also a place where you
put your interpreter which is in this case: /bin/bash.


Here is our first bash shell script example:



#!/bin/bash
# declare STRING variable
STRING="Hello World"
#print variable on a screen
echo $STRING


















Navigate to a directory where your hello_world.sh is located
and make the file executable:



$ chmod +x hello_world.sh 


Make bash shell script executable


Now you are ready to execute your first bash script:



./hello_world.sh 


Example of simple bash shell script

2. Simple Backup
bash shell script



#!/bin/bash
tar -czf myhome_directory.tar.gz /home/linuxconfig












Simple Backup bash script

3. Variables


In this example we declare simple bash variable and print it on the
screen ( stdout ) with echo command.
#!/bin/bash
STRING="HELLO WORLD!!!"
echo $STRING

Bash string Variables in bash script


Your backup script and variables:


#!/bin/bash
OF=myhome_directory_$(date +%Y%m%d).tar.gz
tar -czf $OF /home/linuxconfig

Bash backup Script with bash Variables

3.1. Global vs. Local
variables


#!/bin/bash
#Define bash global variable
#This variable is global and can be used anywhere in this bash script
VAR="global variable"
function bash {
#Define bash local variable
#This variable is local to bash function only
local VAR="local variable"
echo $VAR
}
echo $VAR
bash
# Note the bash global variable did not change
# "local" is bash reserved word
echo $VAR

Global vs. Local Bash variables in bash script

4. Passing
arguments to the bash script


#!/bin/bash
# use predefined variables to access passed arguments
#echo arguments to the shell
echo $1 $2 $3 ' -> echo $1 $2 $3'

# We can also store arguments from bash command line in special array
args=("$@")
#echo arguments to the shell
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'

#use $@ to print out all arguments at once
echo $@ ' -> echo $@'

# use $# variable to print out
# number of arguments passed to the bash script
echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'

/arguments.sh Bash Scripting Tutorial 

Passing arguments to the bash script

5. Executing
shell commands with bash


#!/bin/bash
# use backticks " ` ` " to execute shell command
echo `uname -o`
# executing bash command without backticks
echo uname -o

Executing shell commands with bash

6. Reading User Input


#!/bin/bash

echo -e "Hi, please type the word: \c "
read word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e "How do you feel about bash scripting? "
# read command now stores a reply into the default build-in variable $REPLY
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command to read into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"

Reading User Input with bash

7. Bash Trap Command










#!/bin/bash
# bash trap command
trap bashtrap INT
# bash clear screen command
clear;
# bash trap function is executed when CTRL-C is pressed:
# bash prints message => Executing bash trap subrutine !
bashtrap()
{
echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
echo "$a/10 to Exit."
sleep 1;
done
echo "Exit Bash Trap Example!!!"





8. Arrays


8.1. Declare simple
bash array


#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}

# echo each element in array
# for loop
for (( i=0;i<$ELEMENTS;i++)); do
echo ${ARRAY[${i}]}
done

Declare simple bash array

8.2. Read file into
bash array



#!/bin/bash
#Declare array
declare -a ARRAY
#Open file for reading to array
exec 10
let count=0

while read LINE <&10; do

ARRAY[$count]=$LINE
((count++))
done

echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# close file
exec 10>&-


Read file into bash array

9. Bash if / else /
fi statements


9.1. Simple Bash
if/else statement


Please note the spacing inside the [ and ] brackets! Without the
spaces, it won't work!
#!/bin/bash
directory="./BashScripting"

# bash check if directory exists
if [ -d $directory ]; then
echo "Directory exists"
else
echo "Directory does not exists"
fi

Bash if else fi statement

9.2. Nested if/else


#!/bin/bash

# Declare variable choice and assign value 4
choice=4
# Print to stdout
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"
echo -n "Please choose a word [1,2 or 3]? "
# Loop while the variable choice is equal 4
# bash while loop
while [ $choice -eq 4 ]; do

# read user input
read choice
# bash nested if/else
if [ $choice -eq 1 ] ; then

echo "You have chosen word: Bash"

else

if [ $choice -eq 2 ] ; then
echo "You have chosen word: Scripting"
else

if [ $choice -eq 3 ] ; then
echo "You have chosen word: Tutorial"
else
echo "Please make a choice between 1-3 !"
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"
echo -n "Please choose a word [1,2 or 3]? "
choice=4
fi
fi
fi
done

Nested Bash if else statement

10. Bash Comparisons


10.1. Arithmetic
Comparisons





























-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=

#!/bin/bash
# declare integers
NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values are equal"
else
echo "Values are NOT equal"
fi

Bash Arithmetic Comparisons
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values are equal"
else
echo "Values are NOT equal"
fi

Bash Arithmetic Comparisons - values are NOT equal
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values are equal"
elif [ $NUM1 -gt $NUM2 ]; then
echo "NUM1 is greater then NUM2"
else
echo "NUM2 is greater then NUM1"
fi

Bash Arithmetic Comparisons - greater then

10.2. String Comparisons





























= equal
!= not equal
< less then
> greater then
-n s1string s1 is not empty
-z s1string s1 is empty

#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi

Bash String Comparisons - values are NOT equal
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Bash"
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi

bash interpreter location: /bin/bash

11. Bash File Testing





































































-b filenameBlock special file
-c filenameSpecial character file
-d directorynameCheck for directory existence
-e filenameCheck for file existence
-f filenameCheck for regular file existence not a
directory
-G filenameCheck if file exists and is owned by
effective group ID.
-g filenametrue if file exists and is set-group-id.
-k filenameSticky bit
-L filenameSymbolic link
-O filenameTrue if file exists and is owned by the
effective user id.
-r filenameCheck if file is a readable
-S filenameCheck if file is socket
-s filenameCheck if file is nonzero size
-u filenameCheck if file set-ser-id bit is set
-w filenameCheck if file is writable
-x filenameCheck if file is executable

#!/bin/bash
file="./file"
if [ -e $file ]; then
echo "File exists"
else
echo "File does not exists"
fi

Bash File Testing - File does not exist Bash File Testing - File exists


Similarly
for example we can use while loop to check if file does not exists.
This script will sleep until file does exists. Note bash negator "!"
which negates the -e option.


#!/bin/bash

while [ ! -e myfile ]; do
# Sleep until file does exists/is created
sleep 1
done

12. Loops


12.1. Bash for loop


#!/bin/bash

# bash for loop
for f in $( ls /var/ ); do
echo $f
done

Running for loop from bash shell command line:
$ for f in $( ls /var/ ); do echo $f; done 

Bash for loop

12.2. Bash while loop


#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT-1
done

Bash while loop

12.3. Bash until loop


#!/bin/bash
COUNT=0
# bash until loop
until [ $COUNT -gt 5 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT+1
done

Bash until loop

12.4. Control bash
loop with


Here is a example of while loop controlled by standard input. Until the
redirection chain from STDOUT to STDIN to the read command exists the
while loop continues.
#!/bin/bash
# This bash script will locate and replace spaces
# in the filenames
DIR="."
# Controlling a loop with bash read command by redirecting STDOUT as
# a STDIN to while loop
# find will not truncate filenames containing spaces
find $DIR -type f | while read file; do
# using POSIX class [:space:] to find space in the filename
if [[ "$file" = *[[:space:]]* ]]; then
# substitute space with "_" character and consequently rename the file
mv "$file" `echo $file | tr ' ' '_'`
fi;
# end of while loop
done

Bash script to replace spaces in the filenames with _

13. Bash Functions


!/bin/bash
# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER
function function_B {
echo Function B.
}
function function_A {
echo $1
}
function function_D {
echo Function D.
}
function function_C {
echo $1
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A."
function_B
# Pass parameter to function C
function_C "Function C."
function_D

Bash Functions

14. Bash Select


#!/bin/bash

PS3='Choose one word: '

# bash select
select word in "linux" "bash" "scripting" "tutorial"
do
echo "The word you have selected is: $word"
# Break, otherwise endless loop
break
done

exit 0

Bash Select

15. Case statement
conditional


#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2) perl"
echo "3) phyton"
echo "4) c++"
echo "5) I do not know !"
read case;
#simple case bash structure
# note in this case $case is variable and does not have to
# be named case this is just an example
case $case in
1) echo "You selected bash";;
2) echo "You selected perl";;
3) echo "You selected phyton";;
4) echo "You selected c++";;
5) exit
esac

bash case statement conditiona

16. Bash quotes and
quotations


Quotations and quotes are important part of bash and bash scripting.
Here are some bash quotes and quotations basics.

16.1. Escaping Meta
characters


Before we start with quotes and quotations we should know something
about escaping meta characters. Escaping will suppress a special
meaning of meta characters and therefore meta characters will be read
by bash literally. To do this we need to use backslash "\" character.
Example:
#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

#when meta character such us "$" is escaped with "\" it will be read literally
echo \$BASH_VAR

# backslash has also special meaning and it can be suppressed with yet another "\"
echo "\\"

escaping meta characters in bash

16.2. Single quotes


Single quotes in bash will suppress special meaning of every meta
characters. Therefore meta characters will be read literally. It is not
possible to use another single quote within two single quotes not even
if the single quote is escaped by backslash.
#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

# meta characters special meaning in bash is suppressed when using single quotes
echo '$BASH_VAR "$BASH_VAR"'

Using single quotes in bash

16.3. Double Quotes


Double quotes in bash will suppress special meaning of every meta
characters except "$", "\" and "`". Any other meta characters will be
read literally. It is also possible to use single quote within double
quotes. If we need to use double quotes within double quotes bash can
read them literally when escaping them with "\". Example:
#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

# meta characters and its special meaning in bash is
# suppressed when using double quotes except "$", "\" and "`"

echo "It's $BASH_VAR and \"$BASH_VAR\" using backticks: `date`"

Using double quotes in bash

16.4. Bash
quoting with ANSI-C style


There is also another type of quoting and that is ANSI-C. In this type
of quoting characters escaped with "\" will gain special meaning
according to the ANSI-C standard.







































/aalert (bell)/bbackspace
/ean escape character/fform feed
/nnewline/rcarriage return
/thorizontal tab/vvertical tab
\\backslash\`single quote
\nnnoctal value of characters ( see
[http://www.asciitable.com/ ASCII table] )
\xnnhexadecimal value of characters ( see
[http://www.asciitable.com/ ASCII table] )

The syntax fo ansi-c bash quoting is: $'' . Here is an example:
#!/bin/bash

# as a example we have used \n as a new line, \x40 is hex value for @
# and \56 is octal value for .
echo $'web: www.linuxconfig.org\nemail: web\x40linuxconfig\56org'

quoting in bash with ansi-c stype

17. Arithmetic Operations


17.1. Bash
Addition Calculator Example




#!/bin/bash

let RESULT1=$1+$2
echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2'
declare -i RESULT2
RESULT2=$1+$2
echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2'
echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))'

Bash Addition Calculator

17.2. Bash Arithmetics


#!/bin/bash

echo '### let ###'
# bash addition
let ADDITION=3+5
echo "3 + 5 =" $ADDITION

# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION

# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION

# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION

# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS

# bash power of two
let POWEROFTWO=2**2
echo "2 ^ 2 =" $POWEROFTWO


echo '### Bash Arithmetic Expansion ###'
# There are two formats for arithmetic expansion: $[ expression ]
# and $(( expression #)) its your choice which you use

echo 4 + 5 = $((4 + 5))
echo 7 - 7 = $[ 7 - 7 ]
echo 4 x 6 = $((3 * 2))
echo 6 / 3 = $((6 / 3))
echo 8 % 7 = $((8 % 7))
echo 2 ^ 8 = $[ 2 ** 8 ]


echo '### Declare ###'

echo -e "Please enter two numbers \c"
# read user input
read num1 num2
declare -i result
result=$num1+$num2
echo "Result is:$result "

# bash convert binary number 10001
result=2#10001
echo $result

# bash convert octal number 16
result=8#16
echo $result

# bash convert hex number 0xE6A
result=16#E6A
echo $result

Bash Arithmetic Operations

17.3. Round
floating point number


#!/bin/bash
# get floating point number
floating_point_number=3.3446
echo $floating_point_number
# round floating point number with bash
for bash_rounded_number in $(printf %.0f $floating_point_number); do
echo "Rounded number with bash:" $bash_rounded_number
done

Round floating point number with bash

17.4. Bash
floating point calculations


#!/bin/bash
# Simple linux bash calculator
echo "Enter input:"
read userinput
echo "Result with 2 digits after decimal point:"
echo "scale=2; ${userinput}" | bc
echo "Result with 10 digits after decimal point:"
echo "scale=10; ${userinput}" | bc
echo "Result as rounded integer:"
echo $userinput | bc

Bash floating point calculations

18. Redirections


18.1. STDOUT
from bash script to STDERR


#!/bin/bash

echo "Redirect this STDOUT to STDERR" 1>&2

To proof that STDOUT is redirected to STDERR we can redirect script's
output to file:

STDOUT from bash script to STDERR

18.2. STDERR
from bash script to STDOUT


#!/bin/bash

cat $1 2>&1

To proof that STDERR is redirected to STDOUT we can redirect script's
output to file:

STDERR from bash script to STDOUT

18.3. stdout to screen


The simple way to redirect a standard output ( stdout ) is to simply
use any command, because by default stdout is automatically redirected
to screen.
cat /proc/partitions 

bash stdout to screen

18.4. stdout to file


Here we use ">" to redirect stdout to a file "partitions.txt".
cat /proc/partitions > partitions.txt 

bash stdout to file

18.5. stderr to file


In this example you will redirect the standard error ( stderr ) to a
file and stdout to a default screen.
grep -r hda6 * . 2> stderr.txt 

bash stderr to file

18.6. stdout to stderr


In this case the output of a command will be written to the same
descriptor as a stderr.
grep -r hda6 * . 1>&2 stderr.txt 

bash stdout to stderr

18.7. stderr to stdout


In this case the stderr of a command will be written to the same
descriptor as a stdout.
grep -r hda6 * . 2>&1 stderr.txt 

bash stderr to stdout

18.8. stderr and
stdout to file


grep -r hda6 * . &> stderr_and_stdout.txt 

stderr and stdout to file