Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Monday, January 12, 2015

Bash Script: Number of Arguments

Number of arguments is in variable $#, example is script numarg.sh

#!/bin/bash
echo "number of arguments: $#"

Executing script: 
$ ./numarg.sh arg1 arg2 arg3
Number of arguments: 3

Variable $# doesn't count script name, only arguments.

Arguments are stored in variables $1, $2... or in $@ as array.


Thursday, January 8, 2015

[Bash] Count Letters in a Text File

Bash script have very useful commands for Text File analysis. For this example we will use small part from Leo Tolstoy: War and Peace, available on Project Gutenberg:




This part is placed in file onepart.txt. To count letters all letters must have same case. Command tr will translate all letters to uppercase letters:
$ cat onepart.txt|tr a-z A-Z
Next, output is filtered. Command tr is useful here with first argument are switches -cd and seccond is letter to be filtered. Switch -c means complent and -d to delete, in short those two arguments means erase everything what is not letter in argument.
Pipelining we get:
$ cat onepart.txt|tr a-z A-Z|tr -cd A
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 
Or for B, C etc...

$ cat 3.txt|tr a-z A-Z|tr -cd B
BBBB

$ cat 3.txt|tr a-z A-Z|tr -cd C
CCCCCCCCCCCCCCCCCCCCCCC

 $ cat 3.txt|tr a-z A-Z|tr -cd D
DDDDDDDDDDDDDDDDDDDDDDDDDD

And of course we need to count those letters. Command wc with switch -m do exactly that:

$ cat 3.txt|tr a-z A-Z|tr -cd A|wc -m
40

$ cat 3.txt|tr a-z A-Z|tr -cd B|wc -m
4

$ cat 3.txt|tr a-z A-Z|tr -cd C|wc -m
23

$ cat 3.txt|tr a-z A-Z|tr -cd D|wc -m
26
and, of course, script to count all letters occurances: 

#!/bin/bash

text=$(cat $1|tr a-z A-Z)
echo "Letter occurances:"

for l in A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
do 
let=$(echo $text|tr -cd $l|wc -m)
echo "$l $let"
done
Script is a little bit slower because text is analyzed for every letter.

Monday, May 12, 2014

Bash - Substring

How to get substring in Bash script? Simple :)

if we have string:

$ a=123456789

substring from position 1 to 5 is

$ echo ${a:1:5}
23456

First position in a string is 0.

in general: ${varname:start_pos:length}


Sunday, May 4, 2014

Bash - Exit code

1. Exit code from Bash script

argument of exit command is exit code
exit n
example (exit_example.sh)

#!/bin/bash
exit $1  #return argument 1 as return code

2. Bash last exit code

last exit code is in variable $?

#!/bin/bash
./exit_example.sh 2
echo $?

result is:
2

Wednesday, April 30, 2014

Bash - String Lenght

Getting string length in Bash Script is very easy by using # operator:

$ some_variable="This is Test String"
$ echo ${#some_variable}
19

${#variable_name} gives us string length.

Monday, April 28, 2014

Bash - Ping ip range and email result

In Bash script is a very simple to write script for checking availability of network devices. In this case, the script will ping an address range and rusults will be sent to your email address.

#!/bin/bash
om="mailtempfile"
dat="$(date)"
eval "echo 'This is Computer status from Linips Script at $dat' >${om}"
eval "echo '' >>${om}"

for i in {1..6}
do
    out="$(ping 192.168.1.$i -c 5|tail -1|awk '{print $4}'|cut -d '/' -f 2)"
    case $i in
    1)
        comp="Router One     "
        ;;
    2)
        comp="Router Two     "
        ;;
    3)
        comp="Router Three   "
        ;;
    4)
        comp="Server One     "
        ;;
    5)
        comp="Server Two     "
        ;;
    6)
        comp="Server Three   "
        ;;
    esac
    eval "echo '192.168.1.$i   $comp    $out'>>${om}"
done
mail -s "Net status $dat" myemail@adress <mailtempfile


Or, the same script, with using Bash script arrays:

#!/bin/bash
comp[1]="Router One      "
comp[2]="Router Two      "
comp[3]="Router Three    "
comp[4]="Server One      "
comp[5]="Server Two      "
comp[6]="Server Three    "

om="mailtempfile"
dat="$(date)"
eval "echo 'This is Computer status from Linips Script at $dat' >${om}"
eval "echo '' >>${om}"

for i in {1..6}
do
    out="$(ping 192.168.1.$i -c 5|tail -1|awk '{print $4}'|cut -d '/' -f 2)"
    eval "echo '192.168.1.$i   ${comp[$i]}    $out'>>${om}"
done
mail -s "Net status $dat" myemail@address <mailtempfile



Received email:

This is Computer status from Linips Script at Mon Apr 28 08:13:45 CEST 2014

192.168.1.1   Router One         2.493
192.168.1.2   Router Two         17.712
192.168.1.3   Router Three       13.669
192.168.1.4   Server One         4.601
192.168.1.5   Server Two         8.199
192.168.1.6   Server Three       9.302


And finally, the greatest strenght of this script is that it runs automatically, so you need to add one line in the /etc/crontab file: (example is for script running every 20 min)

*/20  *       * * *     root     /home/user/pingscript..sh

Sunday, April 27, 2014

Bash String Concatenation

If you writing Bash scripts, it's probably happened that you need to concatenate two or more strings. There are several ways to do this:

1. Variable insert

$ a="Hello"
$ b="$a World"
$ echo $b
Hello World

2. Writing variables one after another

$ a="Hello"
$ b=" World"
$ c=$a$b
$ echo $c
Hello World

3. Using += operator

$ a="Hello"
$ a+=" World"
$ echo $a
Hello World




Thursday, April 24, 2014

BASH - customize ping output

Problem is simply: how to get the output of ping command suited to our needs. In this example we will extract average ping time in Bash scripting language.

First let's see output of ping command: ping 192.168.1.1 -c 5 (-c 5 tells to ping command to run five times, else it will run infinitely.)

$ ping 192.168.1.1 -c 5
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=2.62 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=0.477 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=0.482 ms
64 bytes from 192.168.1.1: icmp_seq=4 ttl=64 time=0.482 ms
64 bytes from 192.168.1.1: icmp_seq=5 ttl=64 time=0.487 ms

--- 192.168.1.1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4000ms
rtt min/avg/max/mdev = 0.477/0.911/2.629/0.859 ms

Average ping time is in last line. Use tail -1 to extract only last line. 

$ ping 192.168.1.1 -c 5|tail -1
rtt min/avg/max/mdev = 0.477/0.911/2.629/0.859 ms

Then extract values, count 'arguments' in this line separated by space: 'rtt' is the first, 'min/avg/max/mdev' 2nd, '=' 3rd, '0.477/0.911/2.629/0.859' 4th and 'ms' 5th. 

$ ping 192.168.1.1 -c 5|tail -1|awk '{print $4}'
0.477/0.911/2.629/0.859

and finally, from this output of four '/' separated values, take the second value: this is done by cut command: 

$ ping 192.168.1.1 -c 5|tail -1|awk '{print $4}'|cut -d '/' -f 2
0.911

and this is the value that we are looking for... 

Saturday, February 22, 2014

Linux How to concatenate text files

cat file1 file2 filen > outputfile

or if you want to concatenate all text files in directory:
cat *.txt > outputfile
or you can use >> operator to append to file:
cat file1 >> file2

Friday, February 1, 2013

Bash Conditionals

Conditionals are used when you must make some decision (to execute some part of code or not) by evaluating expression in your script.
For conditionals in Bash scripting language are used clauses: if, then, else.

if (some expression)
then
(do some code)
else
(do some code)

Simplest example is use only if,then

if ["$Var1" = "$Var2"]; then
echo "Variables Var1 and Var2 are equal!"
fi

with clause fi we close if statement.

Other example:

if ["$Var1" = "$Var2"]; then
echo "Variables Var1 and Var 2 are equal!"
else
echo "Variables Var1 and Var2 are NOT equal!"
fi


Variables in Bash script

Variables in Bash script language have following properties:
  • They haven't data type
  • There is no need to declare variable
So, let's see how they works on simple "Hello World" Example:
#!/bin/bash
Var1 = "Hello World!"
echo $Var1
This simple example will output sentence Hello World!

 Interesting with $ sign in Bash is, if you put something in brackets after $ this will be interpreted as interpreter command.
#!/bin/bash
Var1= $(ls -la)
echo $Var1
This simple example will put output from ls -la command in $Var1 variable and then print content on screen.

Important thing about variables is that you can use local variables in functions, using keyword local.

local Var1="Local variable"

Builtin variables

 

 Bash have Built-in variables, some of them are:
  • $BASH - Path to the Bash binary
  • $BASHPID - Process ID of Bash 
  • $BASH_VERSION - Version of Bash
  • $HOME - Home directory of user
  • $MACHTYPE - Machine type
  • $PATH - Path to binaries
  • $PWD - Working directory
  • $SECONDS - number of second while script is running
  • $UID - User ID number
  • $0,$1 ... - Command line arguments
  • $# - Number of command line arguments
And many more...