Sunday, April 9, 2017

Shell Scripting Tutorial for Beginners 20 - FOR loop to execute commands



#!/bin/bash
# for loops

echo "all the files in directory--------"
for item in *
do  
   if [ -f $item ]
   then 
     echo $item
   fi
done

echo
echo "all the directory in directory--------"
for item in *
do  
   if [ -d $item ]
   then 
     echo $item
   fi
done
echo
echo "execute list of commands--------"
for command in ls pwd date
do  
     echo "command name -> $command"
     $command
done

Shell Scripting Tutorial for Beginners 18 - FOR loop



Basic Syntax:



for VARIABLE in 1 2 3 4 5 .. N
do
 command1
 command2
 commandN
done
#OR-----------------------------------------------

for VARIABLE in file1 file2 file3
do
 command1 on $VARIABLE
 command2
 commandN
done
#OR-----------------------------------------------

for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
 command1 on $OUTPUT
 command2 on $OUTPUT
 commandN
done
#OR-----------------------------------------------
for (( EXP1; EXP2; EXP3 ))
do
 command1
 command2
 command3
done




Example:



#!/bin/bash
# for loops
#Example 1 ------------------------
for i in 1 2 3 4 5
do
   echo $i
done

#Example 2 ------------------------
for i in {0..10}
do
   echo $i
done

#Example 3 ------------------------
for i in {0..10..2}
do
   echo $i
done

#Example 4 ------------------------
echo ${BASH_VERSION}
for (( i=0; i<5; i++ ))
do
   echo $i
done

Saturday, April 1, 2017

Shell Scripting Tutorial for Beginners 18 - UNTIL loop



#!/bin/bash
# until loops
n=1

# first way
echo "----until loops------first way-------------------"
until [ $n -gt 10 ]
do
    echo "$n"
    (( n++ ))
done


# second way
n=1
echo "----until loops------second way-------------------"
until (( $n > 10 ))  
do
    echo "$n"
    (( ++n ))
done

# third way
n=1
echo "----until loops------third way-------------------"
until [ $n -gt 10 ]
do
    echo "$n"
    n=$(( n+1 ))
done
output


test@test:~/Desktop$ ./hello.sh 
----until loops------first way-------------------
1
2
3
4
5
6
7
8
9
10
----until loops------second way-------------------
1
2
3
4
5
6
7
8
9
10
----until loops------third way-------------------
1
2
3
4
5
6
7
8
9
10
test@test:~/Desktop$ 

Shell Scripting Tutorial for Beginners 16 - using sleep and open termina...



#!/bin/bash
# while loops
n=1

while [ $n -le 3 ]
do
    echo "$n"
    (( n++ ))
    gnome-terminal &
done

Shell Scripting Tutorial for Beginners 15 - WHILE Loops


#!/bin/bash
# while loops
n=1

# first way
echo "----while loops------first way-------------------"
while [ $n -le 10 ]
do
    echo "$n"
    (( n++ ))
done


# second way
n=1
echo "----while loops------second way-------------------"
while (( $n <= 10 ))  
do
    echo "$n"
    (( ++n ))
done

# third way
n=1
echo "----while loops------third way-------------------"
while [ $n -le 10 ]
do
    echo "$n"
    n=$(( n+1 ))
done
output:
test@test:~/Desktop$ ./hello.sh 
----while loops------first way-------------------
1
2
3
4
5
6
7
8
9
10
----while loops------second way-------------------
1
2
3
4
5
6
7
8
9
10
----while loops------third way-------------------
1
2
3
4
5
6
7
8
9
10
test@test:~/Desktop$ 

Saturday, March 25, 2017

Shell Scripting Tutorial for Beginners 14 - Array variables

#! /bin/bash

os=('ubuntu' 'windows' 'kali')
os[6]='mac'

unset os[2]
echo "${os[@]}"
echo "${os[0]}"
echo "${!os[@]}"
echo "${#os[@]}"

string=dasfdsafsadfasdf
echo "${string[@]}"
echo "${string[0]}"
echo "${string[1]}"
echo "${#string[@]}"

Wednesday, March 22, 2017

Shell Scripting Tutorial for Beginners 13 - The case statement Example



#! /bin/bash

echo -e "Enter some character : \c"
read value


case $value in
    [a-z] )
        echo "User entered $value a to z" ;;
    [A-Z] )
        echo "User entered $value A to Z" ;;
    [0-9] )
        echo "User entered $value 0 to 9" ;;
    ? )
        echo "User entered $value special character" ;;
    * )
        echo "Unknown input" ;;
esac
Output:


test@test$ ./hello.sh 
Enter some character : f
User entered f a to z
test@test$ ./hello.sh 
Enter some character : K
User entered K a to z
test@test$ LANG=C
test@test$ ./hello.sh 
Enter some character : K
User entered K A to Z
test@test$ ./hello.sh 
Enter some character : 9
User entered 9 0 to 9
test@test$ ./hello.sh 
Enter some character : 5
User entered 5 0 to 9
test@test$ ./hello.sh 
Enter some character : &
User entered & special character
test@test$ ./hello.sh 
Enter some character : sdsdsdsd
Unknown input
test@test$ 

Tuesday, March 21, 2017

Shell Scripting Tutorial for Beginners 12 - The case statement

#! /bin/bash

vehicle=$1

case $vehicle in
    "car" )
        echo "Rent of $vehicle is 100 dollar" ;;
    "van" )
        echo "Rent of $vehicle is 80 dollar" ;;
    "bicycle" )
        echo "Rent of $vehicle is 5 dollar" ;;
    "truck" )
        echo "Rent of $vehicle is 150 dollar" ;;
    * )
        echo "Unknown vehicle" ;;
esac

Saturday, March 18, 2017

Shell Scripting Tutorial for Beginners 11 - Floating point math operatio...



#! /bin/bash

num1=20.5
num2=5

echo "$num1+$num2" | bc
echo "$num1-$num2" | bc
echo "20.5*5" | bc
echo "scale=20;20.5/5" | bc
echo "20.5%5" | bc

num=4

echo "scale=2;sqrt($num)" | bc -l
echo "scale=2;3^3" | bc -l

Thursday, March 16, 2017

Shell Scripting Tutorial for Beginners 10 - Perform arithmetic operations

#! /bin/bash

num1=20
num2=5

echo $(( num1 + num2 ))
echo $(( num1 - num2 ))
echo $(( num1 * num2 ))
echo $(( num1 / num2 ))
echo $(( num1 % num2 ))


echo $(expr $num1 + $num2 )
echo $(expr  $num1 - $num2 )
echo $(expr  $num1 \* $num2 )
echo $(expr  $num1 / $num2 )
echo $(expr  $num1 % $num2 )

Wednesday, March 15, 2017

Shell Scripting Tutorial for Beginners 8 - Logical 'OR' Operator



#! /bin/bash

age=60

# for using OR operator use ||
if [ "$age" -gt 18] || ["$age" -lt 30 ]
then
  echo "valid age"
  else
  echo "age not valid"
fi

#  The -o option provide
# an alternative compound condition test.
if [ "$age" -gt 18 -o "$age" -lt 30 ]
then
  echo "valid age"
  else
  echo "age not valid"
fi

# if [[ $condition1 || $condition2 ]]    # Also works.
if [[ "$age" -gt 18 || "$age" -lt 30 ]]
then
  echo "valid age"
  else
  echo "age not valid"
fi

Monday, March 13, 2017

Shell Scripting Tutorial for Beginners 8 - Logical 'AND' Operator

#! /bin/bash

age=60

# for using And operator use &&
if [ "$age" -gt 18] && ["$age" -lt 30 ]
then
  echo "valid age"
  else
  echo "age not valid"
fi

#  The -a option provide
# an alternative compound condition test.
if [ "$age" -gt 18 -a "$age" -lt 30 ]
then
  echo "valid age"
  else
  echo "age not valid"
fi

# if [[ $condition1 && $condition2 ]]    # Also works.
if [[ "$age" -gt 18 && "$age" -lt 30 ]]
then
  echo "valid age"
  else
  echo "age not valid"
fi

Saturday, March 11, 2017

Shell Scripting Tutorial for Beginners 7 - How to append output to the e...



#! /bin/bash

echo -e "Enter the name of the file : \c"
read file_name

if [ -f $file_name ]
then
      if [ -w $file_name ]
      then
         echo "Type some text data. To quit press ctrl+d."
         cat >>  $file_name
      else
          echo "The file do not have write permissions"
      fi
 else   
  echo "$file_name not exists"
fi

Shell Scripting Tutorial for Beginners 6 - File test operators



#! /bin/bash

echo -e "Enter the name of the file : \c"
read file_name

if [ -s $file_name ]
then
  echo "$file_name not empty"
 else   
  echo "$file_name empty"
fi

Monday, March 6, 2017

Shell Scripting Tutorial for Beginners 5 - If Statement ( If then , If t...





Bash Shell

Conditional Statements 
  • Conditionals let us decide whether to perform an action or not, this decision is taken by evaluating an expression. The most basic form is:


      if [ expression ];

      then

            statements

      elif [ expression ];

      then

            statements

      else

            statements

      fi

  • the elif (else if) and else sections are optional
  • Put spaces after [ and before ], and around the operators and operands. 
Bash Shell

Expressions 
  • An expression can be: String comparisonNumeric comparisonFile operators and Logical operators and it is represented by [expression]:
  • String Comparisons: 


=  compare if two strings are equal

!=  compare if two strings are not equal

-n  evaluate if string length is greater than zero

-z  evaluate if string length is equal to zero

  • Examples:


[ s1 = s2 ]  (true if s1 same as s2, else false)

[ s1 != s2 ]  (true if s1 not same as s2, else false)

[ s1 ]   (true if s1 is not empty, else false)

[ -n s1 ]   (true if s1 has a length greater then 0, else false)

[ -z s2 ]   (true if s2 has a length of 0, otherwise false)

Bash Shell

Expressions 
  • Number Comparisons:


-eq compare if two numbers are equal

-ge         compare if one number is greater than or equal to a number

-le  compare if one number is less than or equal to a number

-ne  compare if two numbers are not equal

-gt  compare if one number is greater than another number

-lt  compare if one number is less than another number

  • Examples:


[ n1 -eq n2 ]  (true if n1 same as n2, else false)

[ n1 -ge n2 ]  (true if n1greater then or equal to n2, else false)

[ n1 -le n2 ]  (true if n1 less then or equal to n2, else false)

[ n1 -ne n2 ]  (true if n1 is not same as n2, else false)

[ n1 -gt n2 ]  (true if n1 greater then n2, else false)

[ n1 -lt n2 ]  (true if n1 less then n2, else false)

Bash Shell

Examples 
cat user.sh

 #!/bin/bash

      echo -n “Enter your login name: "

      read name

      if [ “$name” = “$USER” ];

      then

            echo “Hello, $name. How are you today ?”

      else

            echo “You are not $USER, so who are you ?”

      fi

cat number.sh

#!/bin/bash

      echo -n “Enter a number 1 < x < 10: "

      read num

      if [ “$num” -lt 10 ]; then

            if [ “$num” -gt 1 ]; then

                  echo “$num*$num=$(($num*$num))”

            else

                  echo “Wrong insertion !”

            fi

      else

            echo “Wrong insertion !”

      fi





#! /bin/bash

word=a

if  [[ $word == "b" ]]
then
  echo "condition b is true"
elif [[ $word == "a" ]]
then 
  echo "condition a is true" 
else
  echo "condition is false"    
fi

Saturday, March 4, 2017

Shell Scripting Tutorial for Beginners 4 - Pass Arguments to a Bash-Script





#! /bin/bash

# $* Returns a single string (``$1, $2 ... $n'') 
# comprising all of the positional parameters
# separated by the internal field separator character 
#(defined by the IFS environment variable).
# $0 Refers to the name of the script itself
echo $0 $1 $2 $3  ' > echo $1 $2 $3'

# $@ Returns a sequence of strings 
# (``$1'', ``$2'', ... ``$n'')
# wherein each positional parameter 
# remains separate from the others.
args=("$@")

echo ${args[0]} ${args[1]} ${args[2]} 

echo $@

# $# Refers to the number of arguments 
# specified on a command line.
echo $#
output:


test@test$ ./hello.sh Mark Tom John
./hello.sh Mark Tom John  > echo $1 $2 $3
Mark Tom John
Mark Tom John
3

Shell Scripting Tutorial for Beginners 3 - Read User Input



#! /bin/bash
 
echo "Enter name : "
read name
echo "Enterd name : $name"
 
# Multiple inputs
echo "Enter names : "
read name1 name2 name3
echo "Names : $name1 , $name2, $name3"
 
# Two commonly used options however are 
# -p which allows you to specify a prompt
# -s which makes the input silent.
read -p 'username : ' user_var
read -sp 'password : ' pass_var
echo
echo "username : $user_var"
echo "password : $pass_var"
 
# -a makes read command to read into an array
echo "Enter name : "
read -a names
echo "Names : ${names[0]}, ${names[1]}"
 
# read command will now store the reply into the default build-in variable $REPLY
echo "Enter name : "
read 
echo "Name : $REPLY"

Sunday, February 19, 2017

Shell Scripting Tutorial for Beginners 1 - using Variables and Comments



#! /bin/bash
# this is a comment
echo "Hello World" # this is also a comment

echo Our shell name is $BASH
echo Our shell version name is $BASH_VERSION
echo Our home directory is $HOME
echo Our current working directory is $PWD

name=Mark
VALUE=10
echo The name is $name
echo value $VALUE

Tuesday, February 14, 2017

Node.js Tutorial for Beginners 23 - using JavaScript with EJS



Project files

index.js  
node_modules/  
package.json  
views/views/students.ejs



index.js



var express = require('express');
var app = express();

app.set('view engine', 'ejs');

var students = {
    1 : {
        name : 'Mark',
        subjects : ['c++', 'Java', 'c']
    },
    2 : {
        name : 'Tom',
        subjects : ['C#', 'Pthon', 'Mysql']
    },
    3 : {
        name : 'John',
        subjects : ['Javascript', 'Sqlite', 'c']
    },
}

app.get('/students/:id', function(req, rep) {
    rep.render('students', { name : students[req.params.id].name , id : req.params.id
        , subjects : students[req.params.id].subjects});
})

app.listen(3000, function() {
    console.log('our server is live on posrt 3000');
})

package.json

{
  "name": "express_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.5.5",
    "express": "^4.14.1"
  }
}

\views\students.ejs

<html>
    <head>
        <style>
            body {
                background-color: limegreen
            }
        </style>
    </head>
    <body>
        <h1>You have requested the student name : <%= name %></h1>
        <p>id : <%= id %></p>
        <h1>Subjects</h1>
        <ul>
         <% subjects.forEach(function(item) { %>
           <li> <%= item %></li>
         <%});%>
        </ul>
    </body>
</html>

Saturday, February 11, 2017

Node.js Tutorial for Beginners 22 - Node.js template engine EJS in Express





Project files

about.html
index.html
index.js  
node_modules/  
package.json  
views/students.ejs


index.js
var express = require('express');
var app = express();

app.set('view engine', 'ejs');

app.get('/', function(req, rep) {
    rep.sendFile(__dirname + '/index.html');
})

app.get('/about', function(req, rep) {
    rep.sendFile(__dirname + '/about.html');
})

var students = {
    1 : 'Mark',
    2 : 'Tom',
    3 : 'john'
}

app.get('/students/:id', function(req, rep) {
    rep.render('students', { name : students[req.params.id] , id : req.params.id});
})

app.listen(3000, function() {
    console.log('our server is live on posrt 3000');
})

package.json
{
  "name": "express_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.5.5",
    "express": "^4.14.1"
  }
}

\views\students.ejs
<html>
    <head>
        <style>
            body {
                background-color: limegreen
            }
        </style>
    </head>
    <body>
        <h1>You have requested the student name : <%= name %></h1>
        <p>id : <%= id %></p>
    </body>
</html>

index.html
<html>
    <head>
        <style>
            body {
                background-color: limegreen
            }
        </style>
    </head>
    <body>
        <h1>Home Page</h1>
    </body>
</html>


about.html


<html>
    <head>
        <style>
            body {
                background-color: limegreen
            }
        </style>
    </head>
    <body>
        <h1>About Page</h1>
    </body>
</html>

Wednesday, February 8, 2017

Node.js Tutorial for Beginners 21 - Express.js route parameter



var express = require('express');
var app = express();

app.get('/', function(req, rep) {
    rep.send('this is home page');
})

app.get('/about', function(req, rep) {
    rep.send('this is about page');
})

app.get('/contect', function(req, rep) {
    rep.send('this is contect page');
})

var students = {
    1 : 'Mark',
    2 : 'Tom',
    3 : 'john'
}

app.get('/students/:id', function(req, rep) {
    rep.send('you have requested to see the student name : '+ students[req.params.id]);
})

app.listen(3000, function() {
    console.log('our server is live on posrt 3000');
})

Wednesday, February 1, 2017

Node.js Tutorial for Beginners 20 - Introduction to Express.js






$ npm init
This utility will walk you through creating a package.json file.
Press ^C at any time to quit.
name: (express_test) demo
version: (1.0.0)
description: Demo of package.json
entry point: (index.js)
test command:
git repository:
keywords:
author: 
license: (ISC)


 npm install express --save




var express = require('express');

var app = express();
// GET
// POST
// PUT
// DELETE

app.get('/', function(req, rep) {
    rep.send('this is home page');
})

app.get('/about', function(req, rep) {
    rep.send('this is about page');
})

app.get('/contect', function(req, rep) {
    rep.send('this is contect page');
})

app.listen(3000, function() {
    console.log('our server is live on posrt 3000');
})


{
  "name": "express_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.1"
  }
}

Thursday, January 19, 2017

Linux Command Line Tutorial For Beginners 37 - netstat command



NETSTAT(8)                 Linux Programmer's Manual                NETSTAT(8)



NAME
       netstat  - Print network connections, routing tables, interface statis‐
       tics, masquerade connections, and multicast memberships


SYNOPSIS
       netstat  [address_family_options]  [--tcp|-t]   [--udp|-u]   [--raw|-w]
       [--listening|-l]     [--all|-a]     [--numeric|-n]    [--numeric-hosts]
       [--numeric-ports]           [--numeric-users]           [--symbolic|-N]
       [--extend|-e[--extend|-e]]  [--timers|-o] [--program|-p] [--verbose|-v]
       [--continuous|-c]

       netstat              {--route|-r}              [address_family_options]
       [--extend|-e[--extend|-e]]         [--verbose|-v]        [--numeric|-n]
       [--numeric-hosts] [--numeric-ports] [--numeric-users] [--continuous|-c]

       netstat {--interfaces|-i} [--all|-a] [--extend|-e[--extend|-e]] [--ver‐
       bose|-v]  [--program|-p]  [--numeric|-n]  [--numeric-hosts] [--numeric-
       ports] [--numeric-users] [--continuous|-c]

       netstat      {--groups|-g}       [--numeric|-n]       [--numeric-hosts]
       [--numeric-ports] [--numeric-users] [--continuous|-c]

       netstat       {--masquerade|-M}       [--extend|-e]      [--numeric|-n]
       [--numeric-hosts] [--numeric-ports] [--numeric-users] [--continuous|-c]

       netstat {--statistics|-s} [--tcp|-t] [--udp|-u] [--raw|-w]

       netstat {--version|-V}

       netstat {--help|-h}

       address_family_options:

       [-4]      [-6]       [--protocol={inet,unix,ipx,ax25,netrom,ddp}[,...]]
       [--unix|-x] [--inet|--ip] [--ax25] [--ipx] [--netrom] [--ddp]


DESCRIPTION
       Netstat  prints  information about the Linux networking subsystem.  The
       type of information printed is controlled by  the  first  argument,  as
       follows:

   (none)
       By  default,  netstat  displays  a  list of open sockets.  If you don't
       specify any address families, then the active sockets of all configured
       address families will be printed.

   --route , -r
       Display  the kernel routing tables. See the description in route(8) for
       details.  netstat -r and route -e produce the same output.

   --groups , -g
       Display multicast group membership information for IPv4 and IPv6.

   --interfaces, -i
       Display a table of all network interfaces.

   --masquerade , -M
       Display a list of masqueraded connections.

   --statistics , -s
       Display summary statistics for each protocol.

OPTIONS
   --verbose , -v
       Tell the user what is going on by being verbose. Especially print  some
       useful information about unconfigured address families.

   --wide , -W
       Do not truncate IP addresses by using output as wide as needed. This is
       optional for now to not break existing scripts.

   --numeric , -n
       Show numerical addresses instead of trying to determine symbolic  host,
       port or user names.

   --numeric-hosts
       shows  numerical  host  addresses but does not affect the resolution of
       port or user names.

   --numeric-ports
       shows numerical port numbers but does not affect the resolution of host
       or user names.

   --numeric-users
       shows  numerical user IDs but does not affect the resolution of host or
       port names.


   --protocol=family , -A
       Specifies the address families (perhaps better described as  low  level
       protocols)  for  which  connections are to be shown.  family is a comma
       (',') separated list of address family keywords like inet,  unix,  ipx,
       ax25,  netrom,  and ddp.  This has the same effect as using the --inet,
       --unix (-x), --ipx, --ax25, --netrom, and --ddp options.

       The address family inet includes raw, udp and tcp protocol sockets.

   -c, --continuous
       This will cause netstat to print the selected information every  second
       continuously.

   -e, --extend
       Display  additional  information.   Use  this  option twice for maximum
       detail.

   -o, --timers
       Include information related to networking timers.

   -p, --program
       Show the PID and name of the program to which each socket belongs.

   -l, --listening
       Show only listening sockets.  (These are omitted by default.)

   -a, --all
       Show both listening and non-listening sockets.  With  the  --interfaces
       option, show interfaces that are not up

   -F
       Print routing information from the FIB.  (This is the default.)

   -C
       Print routing information from the route cache.

OUTPUT
   Active Internet connections (TCP, UDP, raw)
   Proto
       The protocol (tcp, udp, raw) used by the socket.

   Recv-Q
       The  count  of  bytes  not copied by the user program connected to this
       socket.

   Send-Q
       The count of bytes not acknowledged by the remote host.

   Local Address
       Address and port number of the local end of  the  socket.   Unless  the
       --numeric  (-n)  option is specified, the socket address is resolved to
       its canonical host name (FQDN), and the port number is translated  into
       the corresponding service name.

   Foreign Address
       Address  and port number of the remote end of the socket.  Analogous to
       "Local Address."

   State
       The state of the socket. Since there are no states in raw mode and usu‐
       ally  no  states  used  in UDP, this column may be left blank. Normally
       this can be one of several values:

       ESTABLISHED
              The socket has an established connection.

       SYN_SENT
              The socket is actively attempting to establish a connection.

       SYN_RECV
              A connection request has been received from the network.

       FIN_WAIT1
              The socket is closed, and the connection is shutting down.

       FIN_WAIT2
              Connection is closed, and the socket is waiting for  a  shutdown
              from the remote end.

       TIME_WAIT
              The socket is waiting after close to handle packets still in the
              network.

       CLOSE  The socket is not being used.

       CLOSE_WAIT
              The remote end has shut down, waiting for the socket to close.

       LAST_ACK
              The remote end has shut down, and the socket is closed.  Waiting
              for acknowledgement.

       LISTEN The  socket is listening for incoming connections.  Such sockets
              are not included in the output unless you specify the  --listen‐
              ing (-l) or --all (-a) option.

       CLOSING
              Both  sockets are shut down but we still don't have all our data
              sent.

       UNKNOWN
              The state of the socket is unknown.

   User
       The username or the user id (UID) of the owner of the socket.

   PID/Program name
       Slash-separated pair of the process id (PID) and process  name  of  the
       process  that  owns  the  socket.   --program  causes this column to be
       included.  You will also need superuser privileges to see this informa‐
       tion  on sockets you don't own.  This identification information is not
       yet available for IPX sockets.

   Timer
       (this needs to be written)

   Active UNIX domain Sockets
   Proto
       The protocol (usually unix) used by the socket.

   RefCnt
       The reference count (i.e. attached processes via this socket).

   Flags
       The flags displayed is SO_ACCEPTON (displayed as ACC), SO_WAITDATA  (W)
       or  SO_NOSPACE  (N).   SO_ACCECPTON  is  used on unconnected sockets if
       their corresponding processes are waiting for a  connect  request.  The
       other flags are not of normal interest.

   Type
       There are several types of socket access:

       SOCK_DGRAM
              The socket is used in Datagram (connectionless) mode.

       SOCK_STREAM
              This is a stream (connection) socket.

       SOCK_RAW
              The socket is used as a raw socket.

       SOCK_RDM
              This one serves reliably-delivered messages.

       SOCK_SEQPACKET
              This is a sequential packet socket.

       SOCK_PACKET
              Raw interface access socket.

       UNKNOWN
              Who ever knows what the future will bring us - just fill in here
              :-)

   State
       This field will contain one of the following Keywords:

       FREE   The socket is not allocated

       LISTENING
              The socket is listening for a connection request.  Such  sockets
              are  only  included in the output if you specify the --listening
              (-l) or --all (-a) option.

       CONNECTING
              The socket is about to establish a connection.

       CONNECTED
              The socket is connected.

       DISCONNECTING
              The socket is disconnecting.

       (empty)
              The socket is not connected to another one.

       UNKNOWN
              This state should never happen.

   PID/Program name
       Process ID (PID) and process name of the process that  has  the  socket
       open.  More info available in Active Internet connections section writ‐
       ten above.

   Path
       This is the path name as which the corresponding processes attached  to
       the socket.

   Active IPX sockets
       (this needs to be done by somebody who knows it)

   Active NET/ROM sockets
       (this needs to be done by somebody who knows it)

   Active AX.25 sockets
       (this needs to be done by somebody who knows it)

NOTES
       Starting with Linux release 2.2 netstat -i does not show interface sta‐
       tistics for alias interfaces. To get per alias interface  counters  you
       need to setup explicit rules using the ipchains(8) command.


FILES
       /etc/services -- The services translation file

       /proc  --  Mount  point  for the proc filesystem, which gives access to
       kernel status information via the following files.

       /proc/net/dev -- device information

       /proc/net/raw -- raw socket information

       /proc/net/tcp -- TCP socket information

       /proc/net/udp -- UDP socket information

       /proc/net/igmp -- IGMP multicast information

       /proc/net/unix -- Unix domain socket information

       /proc/net/ipx -- IPX socket information

       /proc/net/ax25 -- AX25 socket information

       /proc/net/appletalk -- DDP (appletalk) socket information

       /proc/net/nr -- NET/ROM socket information

       /proc/net/route -- IP routing information

       /proc/net/ax25_route -- AX25 routing information

       /proc/net/ipx_route -- IPX routing information

       /proc/net/nr_nodes -- NET/ROM nodelist

       /proc/net/nr_neigh -- NET/ROM neighbours

       /proc/net/ip_masquerade -- masqueraded connections

       /proc/net/snmp -- statistics

SEE ALSO
       route(8), ifconfig(8), ipchains(8), iptables(8), proc(5)

BUGS
       Occasionally strange information may appear if a socket changes  as  it
       is viewed. This is unlikely to occur.

AUTHORS
       The   netstat   user   interface   was   written   by  Fred  Baumgarten
       <dc6iq@insu1.etec.uni-karlsruhe.de>, the man  page  basically  by  Matt
       Welsh    <mdw@tc.cornell.edu>.    It    was   updated   by   Alan   Cox
       <Alan.Cox@linux.org> but could do with a bit more work.  It was updated
       again by Tuan Hoang <tqhoang@bigfoot.com>.
       The  man  page  and  the  command  included in the net-tools package is
       totally rewritten by Bernd Eckenfels <ecki@linux.de>.



net-tools                         2008-11-16                        NETSTAT(8)

Monday, January 16, 2017

Linux Command Line Tutorial For Beginners 37 - grep command



GREP(1)               GREP(1)

NAME
       grep,  egrep,  fgrep, zgrep, zegrep, zfgrep, bzgrep, bzegrep, bzfgrep -
       print lines matching a pattern

SYNOPSIS
       grep [options] PATTERN [FILE...]
       grep [options] [-e PATTERN | -f FILE] [FILE...]

DESCRIPTION
       grep searches the named input FILEs (or standard input if no files  are
       named, or the file name - is given) for lines containing a match to the
       given PATTERN.  By default, grep prints the matching lines.

       In addition, two variant programs egrep and fgrep are available.  egrep
       is  the same  as grep -E.  fgrep is the same as grep -F.  zgrep is the
       same as grep -Z.  zegrep is the same as grep -EZ.  zfgrep is  the  same
       as grep -FZ.

OPTIONS
       -A NUM, --after-context=NUM
       Print  NUM  lines  of  trailing  context after  matching lines.
       Places  a  line  containing  --  between contiguous  groups  of
       matches.

       -a, --text
       Process  a binary file as if it were text; this is equivalent to
       the --binary-files=text option.

       -B NUM, --before-context=NUM
       Print NUM  lines of  leading  context  before  matching lines.
       Places  a  line  containing  --  between contiguous  groups  of
       matches.

       -C NUM, --context=NUM
       Print NUM lines of output context.  Places a line containing  --
       between contiguous groups of matches.

       -b, --byte-offset
       Print  the byte offset within the input file before each line of
       output.

       --binary-files=TYPE
       If the first few bytes of a file indicate that the file contains
       binary  data, assume that the file is of type TYPE.  By default,
       TYPE is binary, and grep normally outputs either a one-line mes-
       sage  saying  that a binary file matches, or no message if there
       is no match.  If TYPE is without-match, grep  assumes  that  a
       binary file does not match; this is equivalent to the -I option.
       If TYPE is text, grep processes a binary file  as  if  it  were
       text;  this  is  equivalent  to  the  -a option.  Warning: grep
       --binary-files=text might output binary garbage, which can  have
       nasty side effects if the output is a terminal and if the termi-
       nal driver interprets some of it as commands.

       --colour[=WHEN], --color[=WHEN]
       Surround the matching string with the marker find in  GREP_COLOR
       environment variable. WHEN may be `never', `always', or `auto'

       -c, --count
       Suppress normal output; instead print a count of matching lines
       for each input file.  With the -v,  --invert-match  option  (see
       below), count non-matching lines.

       -D ACTION, --devices=ACTION
       If  an  input  file  is  a device, FIFO or socket, use ACTION to
       process it.  By  default,  ACTION  is  read,  which  means  that
       devices are read just as if they were ordinary files.  If ACTION
       is skip, devices are silently skipped.

       -d ACTION, --directories=ACTION
       If an input file is a directory, use ACTION to process  it.   By
       default, ACTION is read, which means that directories are read
       just as if they were ordinary files.  If ACTION is skip, direc-
       tories  are  silently skipped.  If ACTION is recurse, grep reads
       all files under each directory, recursively; this is  equivalent
       to the -r option.

       -E, --extended-regexp
       Interpret PATTERN as an extended regular expression (see below).

       -e PATTERN, --regexp=PATTERN
       Use PATTERN as the pattern; useful to protect patterns beginning
       with -.

       -F, --fixed-strings
       Interpret  PATTERN as a list of fixed strings, separated by new-
       lines, any of which is to be matched.

       -P, --perl-regexp
       Interpret PATTERN as a Perl regular expression.  This option  is
       not supported in FreeBSD.

       -f FILE, --file=FILE
       Obtain  patterns from  FILE, one per line.  The empty file con-
       tains zero patterns, and therefore matches nothing.

       -G, --basic-regexp
       Interpret PATTERN as a basic  regular  expression  (see  below).
       This is the default.

       -H, --with-filename
       Print the filename for each match.

       -h, --no-filename
       Suppress the  prefixing of  filenames  on output when multiple
       files are searched.

       --help Output a brief help message.

       -I     Process a binary file as if it did not  contain  matching  data;
       this is equivalent to the --binary-files=without-match option.

       -i, --ignore-case
       Ignore  case  distinctions  in  both  the  PATTERN and the input
       files.

       -L, --files-without-match
       Suppress normal output; instead print the  name  of  each  input
       file from which no output would normally have been printed.  The
       scanning will stop on the first match.

       -l, --files-with-matches
       Suppress normal output; instead print the  name  of  each  input
       file  from  which  output would normally have been printed.  The
       scanning will stop on the first match.

       -m NUM, --max-count=NUM
       Stop reading a file after NUM matching lines.  If the  input  is
       standard input  from a regular file, and NUM matching lines are
       output, grep ensures that the standard input  is positioned  to
       just  after the last matching line before exiting, regardless of
       the presence of trailing context lines.  This enables a  calling
       process  to resume a search.  When grep stops after NUM matching
       lines, it outputs any trailing context lines.  When  the -c  or
       --count  option  is  also  used, grep  does  not output a count
       greater than NUM.  When the -v or --invert-match option is  also
       used, grep stops after outputting NUM non-matching lines.

       --mmap If  possible, use the mmap(2) system call to read input, instead
       of the default read(2) system call.  In some situations, --mmap
       yields  better performance.  However, --mmap can cause undefined
       behavior (including core dumps) if an input file shrinks  while
       grep is operating, or if an I/O error occurs.

       -n, --line-number
       Prefix each line of output with the line number within its input
       file.

       -o, --only-matching
       Show only the part of a matching line that matches PATTERN.

       --label=LABEL
       Displays input actually coming from standard input as input com-
       ing  from  file LABEL.  This is especially useful for tools like
       zgrep, e.g.  gzip -cd foo.gz |grep --label=foo something

       --line-buffered
       Flush output on every line.  Note that this incurs a performance
       penalty.

       -q, --quiet, --silent
       Quiet;  do  not write anything to standard output.  Exit immedi-
       ately with zero status if any match is found, even if  an  error
       was detected.  Also see the -s or --no-messages option.

       -R, -r, --recursive
       Read all files under each directory, recursively; this is equiv-
       alent to the -d recurse option.

  --include=PATTERN
       Recurse in directories only searching file matching PATTERN.

  --exclude=PATTERN
       Recurse in directories skip file matching PATTERN.

       -s, --no-messages
       Suppress error messages about nonexistent or  unreadable files.
       Portability note: unlike GNU grep, traditional grep did not con-
       form to POSIX.2, because traditional grep lacked a -q option and
       its  -s option behaved like GNU grep's -q option.  Shell scripts
       intended to be portable to traditional grep should avoid both -q
       and -s and should redirect output to /dev/null instead.

       -U, --binary
       Treat  the  file(s) as binary.  By default, under MS-DOS and MS-
       Windows, grep guesses the file type by looking at  the  contents
       of  the first 32KB read from the file.  If grep decides the file
       is a text file, it strips the CR characters  from  the  original
       file  contents  (to  make  regular expressions with ^ and $ work
       correctly).  Specifying -U overrules this guesswork, causing all
       files  to be read and passed to the matching mechanism verbatim;
       if the file is a text file with CR/LF pairs at the end  of  each
       line,  this  will  cause some regular expressions to fail.  This
       option has no effect on platforms other than MS-DOS and  MS-Win-
       dows.

       -u, --unix-byte-offsets
       Report  Unix-style  byte offsets.   This  switch causes grep to
       report byte offsets as if the file were  Unix-style  text  file,
       i.e. with CR characters stripped off.  This will produce results
       identical to running grep on a Unix machine.  This option has no
       effect  unless -b option is also used; it has no effect on plat-
       forms other than MS-DOS and MS-Windows.

       -V, --version
       Print the version number of grep to standard error.   This  ver-
       sion number should be included in all bug reports (see below).

       -v, --invert-match
       Invert the sense of matching, to select non-matching lines.

       -w, --word-regexp
       Select  only  those  lines  containing  matches  that form whole
       words.  The test is that the matching substring must  either  be
       at  the  beginning  of  the line, or preceded by a non-word con-
       stituent character.  Similarly, it must be either at the end  of
       the line or followed by a non-word constituent character.  Word-
       constituent characters are letters, digits, and the  underscore.

       -x, --line-regexp
       Select only those matches that exactly match the whole line.

       -y     Obsolete synonym for -i.

       --null Output  a  zero  byte  (the  ASCII NUL character) instead of the
       character that normally follows a file name.  For example,  grep
       -l  --null  outputs  a zero byte after each file name instead of
       the usual newline.  This option makes  the  output  unambiguous,
       even in the presence of file names containing unusual characters
       like newlines.  This option can be used with commands like  find
       -print0, perl  -0,  sort  -z, and xargs -0 to process arbitrary
       file names, even those that contain newline characters.

       -Z, --decompress
       Decompress the input data before searching.  This option is only
       available if compiled with zlib(3) library.

       -J, --bz2decompress
       Decompress  the bzip2(1) compressed input data before searching.

REGULAR EXPRESSIONS
       A regular expression is a pattern that  describes  a  set  of  strings.
       Regular expressions  are constructed analogously to arithmetic expres-
       sions, by using various operators to combine smaller expressions.

       grep understands two different versions of regular  expression  syntax:
       "basic" and "extended."  In GNU grep, there is no difference in avail-
       able functionality using  either  syntax.   In  other  implementations,
       basic regular expressions are less powerful.  The following description
       applies to extended regular expressions; differences for basic  regular
       expressions are summarized afterwards.

       The  fundamental building blocks are the regular expressions that match
       a single character.  Most characters, including all letters and digits,
       are  regular expressions that match themselves. Any metacharacter with
       special meaning may be quoted by preceding it with a backslash.

       A bracket expression is a list of characters enclosed by [ and  ].   It
       matches any  single  character in that list; if the first character of
       the list is the caret ^ then it matches any character not in the  list.
       For  example,  the  regular  expression [0123456789] matches any single
       digit.

       Within a bracket expression, a range expression consists of two charac-
       ters separated by a hyphen.  It matches any single character that sorts
       between the two characters, inclusive,  using  the  locale's  collating
       sequence  and  character  set. For  example, in the default C locale,
       [a-d] is equivalent to [abcd].  Many locales sort characters in dictio-
       nary  order,  and in these locales [a-d] is typically not equivalent to
       [abcd]; it might be equivalent to [aBbCcDd], for  example.   To obtain
       the  traditional interpretation of bracket expressions, you can use the
       C locale by setting the LC_ALL environment variable to the value C.

       Finally, certain named classes  of  characters  are  predefined within
       bracket expressions, as follows.  Their names are self explanatory, and
       they  are  [:alnum:],  [:alpha:],  [:blank:],   [:cntrl:],   [:digit:],
       [:graph:],  [:lower:],  [:print:], [:punct:], [:space:], [:upper:], and
       [:xdigit:].  For example, [[:alnum:]]  means  [0-9A-Za-z],  except  the
       latter form depends upon the C locale and the ASCII character encoding,
       whereas the former is independent of locale and character  set.  (Note
       that  the brackets in these class names are part of the symbolic names,
       and must be included in addition to the brackets delimiting the bracket
       list.) Most  metacharacters  lose their special meaning inside lists.
       To include a literal ] place it first  in  the list. Similarly,  to
       include a literal ^ place it anywhere but first.  Finally, to include a
       literal - place it last.

       The period .  matches any single character.  The symbol \w is a synonym
       for [[:alnum:]] and \W is a synonym for [^[:alnum:]].

       The  caret ^ and the dollar sign $ are metacharacters that respectively
       match the empty string at the beginning and end of a line.  The symbols
       \<  and \> respectively match the empty string at the beginning and end
       of a word.  The symbol \b matches the empty string at  the  edge  of  a
       word,  and \B matches the empty string provided it's not at the edge of
       a word.

       A regular expression may be followed by one of several repetition oper-
       ators:
       ?      The preceding item is optional and matched at most once.
       *      The preceding item will be matched zero or more times.
       +      The preceding item will be matched one or more times.
       {n}    The preceding item is matched exactly n times.
       {n,}   The preceding item is matched n or more times.
       {n,m}  The  preceding  item  is matched at least n times, but not more
       than m times.

       Two regular expressions may  be concatenated;  the  resulting  regular
       expression  matches  any  string formed by concatenating two substrings
       that respectively match the concatenated subexpressions.

       Two regular expressions may be joined by  the  infix  operator  |;  the
       resulting  regular expression matches any string matching either subex-
       pression.

       Repetition takes precedence over concatenation, which  in  turn  takes
       precedence  over alternation.  A whole subexpression may be enclosed in
       parentheses to override these precedence rules.

       The backreference \n, where n is a single digit, matches the  substring
       previously  matched by the nth parenthesized subexpression of the regu-
       lar expression.

       In basic regular expressions the metacharacters ?, +, {, |,  (, and  )
       lose  their  special  meaning; instead use the backslashed versions \?,
       \+, \{, \|, \(, and \).

       Traditional egrep did not support the { metacharacter, and  some  egrep
       implementations support \{ instead, so portable scripts should avoid {
       in egrep patterns and should use [{] to match a literal {.

       GNU egrep attempts to support traditional usage by assuming that  {  is
       not  special if it would be the start of an invalid interval specifica-
       tion.  For example, the shell command egrep '{1' searches for the  two-
       character  string {1 instead of reporting a syntax error in the regular
       expression.  POSIX.2 allows this behavior as an extension, but portable
       scripts should avoid it.

ENVIRONMENT VARIABLES
       Grep's behavior is affected by the following environment variables.

       A  locale  LC_foo is specified by examining the three environment vari-
       ables LC_ALL, LC_foo, LANG, in that order.  The first  of  these  vari-
       ables  that is set specifies the locale.  For example, if LC_ALL is not
       set, but LC_MESSAGES is set to pt_BR, then Brazilian Portuguese is used
       for  the  LC_MESSAGES  locale. The  C locale is used if none of these
       environment variables  are  set,  or  if  the  locale  catalog  is  not
       installed,  or  if grep was not compiled with national language support
       (NLS).

       GREP_OPTIONS
       This variable specifies default options to be placed in front of
       any   explicit   options.    For example,  if  GREP_OPTIONS  is
       '--binary-files=without-match --directories=skip', grep  behaves
       as  if the two options --binary-files=without-match and --direc-
       tories=skip had been  specified  before  any  explicit  options.
       Option  specifications are separated by whitespace.  A backslash
       escapes the next character, so it can  be  used  to  specify  an
       option containing whitespace or a backslash.

       GREP_COLOR
       Specifies the marker for highlighting.

       LC_ALL, LC_COLLATE, LANG
       These  variables specify the LC_COLLATE locale, which determines
       the collating sequence used to interpret range expressions  like
       [a-z].

       LC_ALL, LC_CTYPE, LANG
       These  variables specify  the LC_CTYPE locale, which determines
       the type of characters, e.g., which characters are whitespace.

       LC_ALL, LC_MESSAGES, LANG
       These variables specify the LC_MESSAGES locale, which determines
       the  language that grep uses for messages.  The default C locale
       uses American English messages.

       POSIXLY_CORRECT
       If set,  grep  behaves  as  POSIX.2  requires;  otherwise,  grep
       behaves  more  like  other  GNU programs.  POSIX.2 requires that
       options that follow file names must be treated as file names; by
       default, such  options are permuted to the front of the operand
       list and are treated as options. Also,  POSIX.2 requires  that
       unrecognized  options  be diagnosed as "illegal", but since they
       are not really against the law the default is to diagnose  them
       as "invalid".

DIAGNOSTICS
       Normally, exit status is 0 if selected lines are found and 1 otherwise.
       But the exit status is 2 if an error occurred, unless the -q or --quiet
       or --silent option is used and a selected line is found.

BUGS
       Email  bug  reports  to bug-gnu-utils@gnu.org. Be sure to include the
       word "grep" somewhere in the "Subject:" field.

       Large repetition counts in the {n,m} construct may cause  grep  to  use
       lots of memory. In addition, certain other obscure regular expressions
       require exponential time and space, and may cause grep to  run  out  of
       memory.

       Backreferences are very slow, and may require exponential time.

GNU Project     2002/01/22          GREP(1)