Linux and Shell Scriting

 



Linux is a family of open source Unix like operating system based on the Linux kernel, an operating system kernel first release on September 17,1991 by Linus Torvalds 



Linux Kernel is the core interface between a computer's hardware and its processes


What does the kernel do?

The kernel has 4 jobs:

  1. Memory management: Keep track of how much memory is used to store what and where
  2. Process management: Determine which processes can use the central processing unit(CPU) when and for how long
  3. Device drivers: Act as mediator/interpreter between the hardware and processes
  4. System calls and security: Receive request for service from the process
Directory structure





/ - The root directory

Everything , all the files and directories , in Linux are located under root represented by '/'

what is shell?
Shell is a program which provides the direct interaction with the operating system.
e.g. windows cmd







Shell Types

In Unix, there are two major types of shells −

  • Bourne shell − If you are using a Bourne-type shell, the $ character is the default prompt.

  • C shell − If you are using a C-type shell, the % character is the default prompt.

The Bourne Shell has the following subcategories −

  • Bourne shell (sh)
  • Korn shell (ksh)
  • Bourne Again shell (bash)
  • POSIX shell (sh)

The different C-type shells follow −

  • C shell (csh)
  • TENEX/TOPS C shell (tcsh)

Compiler vs Interpreter



Shell scripts have certain advantages over compiler-based programs, such as C or C++ language. However, Shell scripting has certain limitations as well.




The following are the advantages:

  • Script are easy to write
  • scripts are quick to start and easy to debug
  • They save the time of development
  • Task of administration are automated
  • No addition setup or tools are required for developing or testing shell script

Following are the limitation of shell scripts
  • every line in shell scripts creates a new process in the OS. When we executes the compiled program such as C program it run as a single process for complete program
  • since every command creates a new process , shell scripts are slow as compared to compiled programs
  • Shell Scripts are not suitable if heavy math operation are involved
  • There are problems with cross platform portability
  • We cannot use shell scripts in the following situations when
    1. Extensive file operations are required
    2. we need data structure such as linked list or trees
    3. we need to generate or manipulate graphics or GUIs
    4. we need direct access to system hardware
    5. We need a port or socket I/O
    6. we need to use library or interface with legacy code
    7. Proprietary closed source application are used (Shell scripts put the source code right out in the open for the entire world to see) 


You can simply practice Linux command in replit.com
General Linux Command with its features

ls
it is used to display all the files and folder present in current directory.  It allows you to list the contents of the directory you want (the current directory by default), including files and other nested directories.

pwd 
The pwd command stands for “print working directory,” and it outputs the absolute path of the directory you’re in. For example, if your username is “john” and you’re in your Documents directory, its absolute path would be: /home/john/Documents


date
date command is used to get and set system date

whoami
this command is used to display the user name

du
The du command is a standard Linux/Unix command that allows a user to gain disk usage information quickly. It is best applied to specific directories and allows many variations for customizing the output to meet your needs.


df
The df command (short for disk free), is used to display information related to file systems about total space and available space.

echo
echo is a command that outputs the strings that are passed to it as arguments. It is a command available in various operating system shells and typically used in shell scripts and batch files to output status text to the screen or a computer file, or as a source part of a pipeline.

touch
It is used to create a file without any content. The file created using touch command is empty. This command can be used when the user doesn’t have data to store at the time of file creation.


cp

It’s so easy to copy files and folders directly in the Linux terminal that sometimes it can replace conventional file managers.

To use the cp command, just type it along with the source and destination files:


cp file_to_copyt.txt new_file.txt


mv

You use the mv command to move (or rename) files and directories through your file system.

To use this command, you’d type its name with the source and destination files:



mv source_file destination_folder



mkdir

mkdir command is used to make new directory or folder


rmdir

rmdir command is used to delete directory


rm

rm command is used to remove objects such as computer files, directories and symbolic links from file systems and also special files such as device nodes, pipes and sockets, similar to the del command in MS-DOS, OS/2, and Microsoft Windows


head and tail

the head command will output the first part of the file, while the tail command will print the last part of the file. Both commands write the result to standard output.


cat 

The cat command is a utility command in Linux. One of its most commonly known usages is to print the content of a file onto the standard output stream. Other than that, the cat command also allows us to write some texts into a file.

cat > sometxtfile

text to written

ctrl + C


more is the oldest , less is improvement

more : forward navigation and limited backward navigation

less: both forward and backward navigation and also has search option. You can go to the beginning and the end of file instantly. Plus you can switch to an editor (like open the file in vi or vm) It is noticeably quicker than editor for when the file is large



vi

The VI editor is the most popular and classic text editor in the Linux family.

write and edit text

:wq exit



nano command is used to open different types of file


sleep



grep


top


ps



free



find



I pipe




File permission and ownership 

chmod

file permission and ownership

change file permission with chmod and ownership with chown

$chmod 755 filename.txt

changes file permission to rwx for owner and rx for group and others


read r= 4

write w = 2

execute x=1



chown chown owner: group filename

chown newuser: runner newFile



chown owner: group filename


chown ubntu:www-data newfile.ph



chgrp

this command changes the group ownership of each given file to group (which can be either a group or a numeric group id) or to match the same group as an existing reference file


chgrp oracleadin/usr/database


we can write these command in .sh file and run the script very conviently


# refers to comment

echo "hello world"

#echo is simply used to print string

ls

date

#we'll take input from user

#show output back to screen

read -p "What is your name?" name

echo "hello $name, let's learn shell scripting together"



passing input as a parameter while executing srits

$./name.sh "Jidesh"

read -p "What's your name?" "$1"

echo "Hello $1, shell scripting is cool"










operator


logical

&&

||

!

>

<

>=

<=

!=

==



arithmetic operator

+

-

/

*

%

** exponent

++ increase by 1

-- decrease by 1


conditional statement

if else


syntax

if [] [[]]

POSIX

test




-eq  equal

-ne !=

-gt >

-lt<

ge ?=

le <=



eg

num1=123

num2=200

if [[ num1 -gt num2 ]];

    echo "$num1 is greater than $num2"

else

        echo "$num2 is greater than $num1"

fi



read -p "enter a number: " x

if [[ $x -ne 0 && $x%2 -eq 0 ]]; then

    echo "$x s even number";

elif [[ $x%2 -ne 0 ]]; then

    ehco "$x is odd number"

elif [[ $x -eq 0 ]];

    echo "$x is neither even nor odd"

fi



switch case

read -p "Please give me a choice: " color

case $color in

red)

    echo "The color is red";

;;

green)

    echo "The color is green";

;;

yellow)

    echo "the color is yellow";

;;

*)

    echo :"couldn't guess"


esac




to run sub shell command $(data +%s)



epoch=$(date +%S)

echo $epoch


#!/bin/bash

#written in first line so that ./ will execute


array = (1 2 3 4 5 6 )

select user, address, gender from users;

select user || '-' || address || '-' || gender from users;


num = "1 ,2, 3, 4, 5"

echo "size of nums array: ${#nums[@]}"


IFS= ',' READ -r -a numArray <<<"$nums"

echo "New array: ${numArray[@]}"

len = ${#newArray[@]}

echo "Length of new array:$len"


#table multiple database servers user, password, hostname

select user||'|||password||'|'||'|'||hostname from db_server;

'oracle|admin|server1.cotiviti.com"

'oracle|admin|server2.cotiviti.com"

'oracle|admin|server3.cotiviti.com"


connection_string="string"

sqlplus user/password@connectionstring.com



IFS='|' read-r -a config <<<"$configurations"


user=${coonfig[0]}

passwd=${config[1]}

server=${config[2]}

mysql -u $user -p $password -h $server



loop


for loop  syntax


for (( i=0; $i<10; i++)); do

    echo "$i";

done



for i in {0..10}; do

   echo "$i"

done


list="Apple cat orange cow";

    for element in $list; do

        echo "$element";

    done


list="Apple| cat fish| orange| cow";

IFS='|' read -r -a animal <<<"$list"

len=${#animal[@]}

for (($i=0;$i<$len;$i++)); do

    echo "Name of the anmal: ${animal[$i]}"

done


use $ sign only to access value




for name in $[animal[@]}; do

    echo "Name of the animal $name"

done





    for element in $list; do

        echo "$element";

    done


while loop


counter=1

while [[ $counter -le 10 ]]; do

    echo $counter

((counter++))

done






using break in a loop

for ((i=1l<=10;i++)); do

    echo $

if [$i -eq 3]; then

    break

fi

done



using continue in a loop

for (( i=0;i<=20;i++)); do 

    if [$(($i%2)) -ne 1]; then

        continue

fi

echo $i

done



#using continue n loop

for ((i=0;i<=20;i++); do

    if[ $(($i %2)) -ne 10]; di

        echo $counter

        (counter++)

done

echo "Reached end of loop"


while loop

while [[ $counter -lt 10 ]]; do

    echo $counter

((counter ++))

done


echo "reach end of loop"


until loop num=1

until [[ $num -gt 10 ]]; do

    echo $(($num*3))

    num=$(($num+1))

done

echo "reached end of loop:



Comments