SlideShare a Scribd company logo
introduction of
the shell script
basic sh and shell script usage
2013 usagi@WonderRabbitProject.net CC0
what's the shell script?
● it's a language
   ○ script language // like a C style
     ■ procedural model
     ■ function is available
     ■ variable is available
     ■ type system is not available // so text based
     ■ can call an external routine // system call
● it's as same the shell-self
   ○ APIs are commands on the system
if you learned a C style language
● control statements
  ○ loop
    ■ `for`
    ■ `while` // and `until`
  ○ conditional branching
    ■ `if`
    ■ `case` // equiv switch
● function and variable
  ○ `f(){}` // equiv `void f(void){}`
    ■ how to use input params and a return? --> next!
  ○ `ABC=hoge` // equiv `char* ABC = "hoge"`
    ■ and more --> next!!
how to use function
● how to get input params?
  ○ f(){ echo $1; echo $2; echo $3; }
    ■ it's equiv in C style:
        void f(char* a, char* b, char* c)
        { puts(a); puts(b); puts(c); }
● how to put return value?
  ○ n/a // shell script has not C style return value!
    ■ but, it has return code as same the system call
● how call function?
  ○ f hoge fuga piyo
    ■ it's equiv in C style
        f("hoge", "fuga", "piyo")
return value of function call
● n/a
● but, can use static variables and a trick
  ○ trick
    # define // it's line comment use the char of `#`
    f(){ echo "it's return value!"; }
    # call and get return value trick with backquote '`'
    RETURN_VALUE = `f`
    # and print
    echo $RETURN_VALUE
    ■ what's `$` token?
         ●   --> it's a variable to next!
how to use a variable?
● define a variable
  ○ HOGE=hogehogehoge
    FUGA=fugafugafuga
    num_of_my_awesome_defition=123456
● reference a variable
  ○ echo $HOGE
    echo "$HOGE-$FUGA"
    echo $num_of_my_awesome_definition >> $hoge
variable tips-1
● a variable is only string type
   ○ abc=1234 # quiv to abc="1234"
     # it's not a number
● writing rules
   ○ standard definition
     ■ abc=hogehoge # it's ok
     ■ abc = fugafuga # ERROR! it's a function call
        # $1='=', $2='fugafuga'; hint is white-space.
   ○ explicit value
     ■ def='#abc $abc @abc' # equiv: #abc $abc @abc
     ■ def="#abc $abc @abc'
        # equiv: #abc fugafuga @abc
variable tips-2
● implicit defined special values
   ○ $1 $2 $3 ...
     it's params by a function call or run a script with
     params.
     # f(){ echo $1; }
     // int main(int ac, char** params) { }
   ○ $#
     it's number of params
     # f(){ echo $#; }
     // int main(int ac, char** params) { }
   ○ $?
     it's a last result code (success or else)
     # echo $?
let's run a shell script
> pwd
/home/myname
> # it's comment line
> my_awesome_variable=1234
> echo $my_awesome_variable
1234
> my_awesome_function(){ echo $1; }
> my_awesome_function hoge
hoge
save to file a shell script
> echo 'echo $1' > my_awesome.sh
> cat my_awesome.sh
echo $1

you can write with the Vim or the other text
editor as you like if you want to use.

> vim my_aersome2.sh
run a shell script from a file
● run the other process on the process
  > sh my_awesome.sh hoge
  hoge
  > bash my_awesome.sh fuga
  fuga
● run in the process
  > source my_awesome.sh piyo
  piyo
environment variable
● variable
  ○ shell-variable
    it's only visible from the shell process.
    > abc=hoge
    > sh <-- run a child process
    >> echo $abc <-- it's put the empty string
    >> exit
    > echo $abc <-- it's puts 'hoge'
  ○ environment-varialbe
    it's visible from the shell and child processes.
    > export abc=hoge
    > sh
    >> echo $abc <-- it's puts 'hoge'
shebang and executable-file
● shebang
  ○ > vim hoge.sh
        #!/bin/sh <-- it's shebang liine
        echo $1
● executable-file
  ○ set the executable flag
    > chmod +x hoge.sh
  ○ run
    > ./hoge.sh <-- don't forget path before filename!
    ■ hint: see the $PATH environment variable. it's
        search path for a command on your system. and
        think with a security policy.
shebang for any script-files
● shell script
  #!/bin/sh
● node.js script
  #!/usr/bin/node
● python script
  #!/usr/bin/python
● php script
  #!/usr/bin/php
● haskell script
  #!/usr/bin/runhaskell
     hint: > file hoge.sh
`for` statement
and an array like variable
# it's like an array separated by the space char
values='aaa bbb ccc'

# like the foreach in Java or for-in in JS
for value in $values
do
 echo $value
done
`seq` command
> seq 8
1
2
3
4
5
6
7
8
`...` <-- it's the back-quote pair,
not a single-quote pair('...')
# if use the single-quote pair
> echo 'seq 512 64 768'
seq 512 64 768
# if use the back-quote pair
> echo `seq 512 64 768`
512 576 640 704 768 <-- it's like an array string

the back-quote pattern is like an eval() in JS.
it's run a text as a script code. be cautious!
`for` statement
with `seq` command and ` pattern
it's give a loop with a numeric sequence.

for value in `seq 0 15`
do
 echo $value
done
`while` and `until` statements
● while <-- if true then loop
    while true
    do
      echo '\(^o^)/'
    done
● until <-- if false then loop
    until false
    do
      echo '/(^o^)\'
    done
`test` command for comparison
>   test 3 -eq 4 <-- equiv (3 == 4)
>   echo $?
1   <-- so false in shell-script
>   test 3 -ne 4 <-- equiv (3 != 4)
>   echo $?
0   <-- so true in shell-script
>   test 3 -gt 4 <-- equiv (3 > 4)
>   echo $?
1   <-- so false in shell-script
`test` command for file check
>   test -f /proc/cpuinfo <-- is the file available
>   echo $?
0
>   test -d /boot <-- is the directory available
>   echo $?
0
`expr` command
for calc a number from a string
# it's ng, not calc
> echo 1 + 2 + 4

#   it's ok, calc
>   echo `expr 1 + 2 + 4`
7
>   expr 5 + ( 5 - 5 ) * 5 / 5 % 5
5
#   note: ( ) * <-- need  escape-sequence.
`until` statement
with `test`, `expr` and ` pattern
it's give a loop with a numeric counter.

counter=15
until `test $counter -eq 0`
do
 echo $counter
 counter=`expr $counter - 1`
done
`if` statement
# if.sh                > source if.sh
f(){
                       >f0
  if test $1 -lt 0
  then                 zero
    echo 'negative'    >f1
  elif test $1 -gt 0   positive
  then
    echo 'positive'
                       > f -1
  else                 negative
    echo 'zero'
  fi
}
`case` statement
# case.sh              > source case.sh
f(){
                       >f0
  case $1 in
  0)                   zerp
   echo 'zero';;       >f5
  1)                   two-nine
   echo 'one';;
  [2-9])
                       > f -1
   echo 'two-nine';;   ????
  default)
   echo '????'
  esac
}
where are more information?
all of the information is
available on the man
pages. see the man pages.
man page is the best
unified answerer for all
GNU/Linux users.

> man sh

More Related Content

What's hot (20)

PDF
Advanced modulinos trial
brian d foy
 
PDF
Learning Perl 6
brian d foy
 
PDF
CLI, the other SAPI phpnw11
Combell NV
 
ODP
The promise of asynchronous PHP
Wim Godden
 
PDF
Functional Programming in PHP
pwmosquito
 
PDF
Learning Perl 6 (NPW 2007)
brian d foy
 
PDF
De 0 a 100 con Bash Shell Scripting y AWK
Adolfo Sanz De Diego
 
PDF
What's new in PHP 8.0?
Nikita Popov
 
PDF
2014 database - course 2 - php
Hung-yu Lin
 
PDF
Advanced modulinos
brian d foy
 
PDF
Module 03 Programming on Linux
Tushar B Kute
 
PDF
PerlScripting
Aureliano Bombarely
 
PDF
PHP Enums - PHPCon Japan 2021
Ayesh Karunaratne
 
PDF
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
PDF
9 character string &amp; string library
MomenMostafa
 
PPT
Advanced php
Anne Lee
 
PDF
PerlTesting
Aureliano Bombarely
 
PDF
6 c control statements branching &amp; jumping
MomenMostafa
 
PDF
OSDC.TW - Gutscript for PHP haters
Lin Yo-An
 
PDF
Perl 6 by example
Andrew Shitov
 
Advanced modulinos trial
brian d foy
 
Learning Perl 6
brian d foy
 
CLI, the other SAPI phpnw11
Combell NV
 
The promise of asynchronous PHP
Wim Godden
 
Functional Programming in PHP
pwmosquito
 
Learning Perl 6 (NPW 2007)
brian d foy
 
De 0 a 100 con Bash Shell Scripting y AWK
Adolfo Sanz De Diego
 
What's new in PHP 8.0?
Nikita Popov
 
2014 database - course 2 - php
Hung-yu Lin
 
Advanced modulinos
brian d foy
 
Module 03 Programming on Linux
Tushar B Kute
 
PerlScripting
Aureliano Bombarely
 
PHP Enums - PHPCon Japan 2021
Ayesh Karunaratne
 
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
9 character string &amp; string library
MomenMostafa
 
Advanced php
Anne Lee
 
PerlTesting
Aureliano Bombarely
 
6 c control statements branching &amp; jumping
MomenMostafa
 
OSDC.TW - Gutscript for PHP haters
Lin Yo-An
 
Perl 6 by example
Andrew Shitov
 

Viewers also liked (8)

PDF
Mastering the MongoDB Shell
MongoDB
 
PPTX
Shell Script Tutorial
Quang Minh Đoàn
 
PDF
Text mining on the command line - Introduction to linux for bioinformatics
BITS
 
PPT
Shell Scripting
Gaurav Shinde
 
PPT
Unix Shell Scripting Basics
Dr.Ravi
 
PDF
003 scripting
Sherif Mousa
 
PPTX
Unix shell scripts
Prakash Lambha
 
PPTX
H
anaferrom3
 
Mastering the MongoDB Shell
MongoDB
 
Shell Script Tutorial
Quang Minh Đoàn
 
Text mining on the command line - Introduction to linux for bioinformatics
BITS
 
Shell Scripting
Gaurav Shinde
 
Unix Shell Scripting Basics
Dr.Ravi
 
003 scripting
Sherif Mousa
 
Unix shell scripts
Prakash Lambha
 
Ad

Similar to Linux shell script-1 (20)

PPTX
php programming.pptx
rani marri
 
PPT
Shell Scripts
Dr.Ravi
 
PDF
Operating_System_Lab_ClassOperating_System_2.pdf
DharmatejMallampati
 
PPTX
shellScriptAlt.pptx
NiladriDey18
 
PPT
34-shell-programming asda asda asd asd.ppt
poyotero
 
PPT
Web Technology_10.ppt
Aftabali702240
 
PDF
OS.pdf
ErPawanKumar3
 
PPT
34-shell-programming.ppt
KiranMantri
 
PDF
Shell Programming_Module2_Part2.pptx.pdf
HIMANKMISHRA2
 
PPTX
Unix Shell Programming subject shell scripting ppt
Radhika Ajadka
 
PDF
How to run PHP code in XAMPP.docx (1).pdf
rajeswaria21
 
PDF
SymfonyCon 2017 php7 performances
julien pauli
 
DOCX
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
MARRY7
 
DOCX
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
adkinspaige22
 
PPTX
AOS_Module_3ssssssssssssssssssssssssssss.pptx
rapiwip803
 
PDF
Web 8 | Introduction to PHP
Mohammad Imam Hossain
 
PPTX
Introduction in php
Bozhidar Boshnakov
 
PPTX
KT on Bash Script.pptx
gogulasivannarayana
 
PPT
Shell programming
Moayad Moawiah
 
PPT
Php basics
hamfu
 
php programming.pptx
rani marri
 
Shell Scripts
Dr.Ravi
 
Operating_System_Lab_ClassOperating_System_2.pdf
DharmatejMallampati
 
shellScriptAlt.pptx
NiladriDey18
 
34-shell-programming asda asda asd asd.ppt
poyotero
 
Web Technology_10.ppt
Aftabali702240
 
34-shell-programming.ppt
KiranMantri
 
Shell Programming_Module2_Part2.pptx.pdf
HIMANKMISHRA2
 
Unix Shell Programming subject shell scripting ppt
Radhika Ajadka
 
How to run PHP code in XAMPP.docx (1).pdf
rajeswaria21
 
SymfonyCon 2017 php7 performances
julien pauli
 
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
MARRY7
 
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
adkinspaige22
 
AOS_Module_3ssssssssssssssssssssssssssss.pptx
rapiwip803
 
Web 8 | Introduction to PHP
Mohammad Imam Hossain
 
Introduction in php
Bozhidar Boshnakov
 
KT on Bash Script.pptx
gogulasivannarayana
 
Shell programming
Moayad Moawiah
 
Php basics
hamfu
 
Ad

Recently uploaded (20)

PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PDF
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
PPTX
ENG8_Q1_WEEK2_LESSON1. Presentation pptx
marawehsvinetshe
 
PPTX
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
PPTX
GENERAL BIOLOGY 1 - Subject Introduction
marvinnbustamante1
 
PPTX
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
PPTX
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PPTX
Navigating English Key Stage 2 lerning needs.pptx
JaysonClosa3
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPT
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PPTX
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
ENG8_Q1_WEEK2_LESSON1. Presentation pptx
marawehsvinetshe
 
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
GENERAL BIOLOGY 1 - Subject Introduction
marvinnbustamante1
 
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
Navigating English Key Stage 2 lerning needs.pptx
JaysonClosa3
 
Introduction to Indian Writing in English
Trushali Dodiya
 
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 

Linux shell script-1

  • 1. introduction of the shell script basic sh and shell script usage 2013 [email protected] CC0
  • 2. what's the shell script? ● it's a language ○ script language // like a C style ■ procedural model ■ function is available ■ variable is available ■ type system is not available // so text based ■ can call an external routine // system call ● it's as same the shell-self ○ APIs are commands on the system
  • 3. if you learned a C style language ● control statements ○ loop ■ `for` ■ `while` // and `until` ○ conditional branching ■ `if` ■ `case` // equiv switch ● function and variable ○ `f(){}` // equiv `void f(void){}` ■ how to use input params and a return? --> next! ○ `ABC=hoge` // equiv `char* ABC = "hoge"` ■ and more --> next!!
  • 4. how to use function ● how to get input params? ○ f(){ echo $1; echo $2; echo $3; } ■ it's equiv in C style: void f(char* a, char* b, char* c) { puts(a); puts(b); puts(c); } ● how to put return value? ○ n/a // shell script has not C style return value! ■ but, it has return code as same the system call ● how call function? ○ f hoge fuga piyo ■ it's equiv in C style f("hoge", "fuga", "piyo")
  • 5. return value of function call ● n/a ● but, can use static variables and a trick ○ trick # define // it's line comment use the char of `#` f(){ echo "it's return value!"; } # call and get return value trick with backquote '`' RETURN_VALUE = `f` # and print echo $RETURN_VALUE ■ what's `$` token? ● --> it's a variable to next!
  • 6. how to use a variable? ● define a variable ○ HOGE=hogehogehoge FUGA=fugafugafuga num_of_my_awesome_defition=123456 ● reference a variable ○ echo $HOGE echo "$HOGE-$FUGA" echo $num_of_my_awesome_definition >> $hoge
  • 7. variable tips-1 ● a variable is only string type ○ abc=1234 # quiv to abc="1234" # it's not a number ● writing rules ○ standard definition ■ abc=hogehoge # it's ok ■ abc = fugafuga # ERROR! it's a function call # $1='=', $2='fugafuga'; hint is white-space. ○ explicit value ■ def='#abc $abc @abc' # equiv: #abc $abc @abc ■ def="#abc $abc @abc' # equiv: #abc fugafuga @abc
  • 8. variable tips-2 ● implicit defined special values ○ $1 $2 $3 ... it's params by a function call or run a script with params. # f(){ echo $1; } // int main(int ac, char** params) { } ○ $# it's number of params # f(){ echo $#; } // int main(int ac, char** params) { } ○ $? it's a last result code (success or else) # echo $?
  • 9. let's run a shell script > pwd /home/myname > # it's comment line > my_awesome_variable=1234 > echo $my_awesome_variable 1234 > my_awesome_function(){ echo $1; } > my_awesome_function hoge hoge
  • 10. save to file a shell script > echo 'echo $1' > my_awesome.sh > cat my_awesome.sh echo $1 you can write with the Vim or the other text editor as you like if you want to use. > vim my_aersome2.sh
  • 11. run a shell script from a file ● run the other process on the process > sh my_awesome.sh hoge hoge > bash my_awesome.sh fuga fuga ● run in the process > source my_awesome.sh piyo piyo
  • 12. environment variable ● variable ○ shell-variable it's only visible from the shell process. > abc=hoge > sh <-- run a child process >> echo $abc <-- it's put the empty string >> exit > echo $abc <-- it's puts 'hoge' ○ environment-varialbe it's visible from the shell and child processes. > export abc=hoge > sh >> echo $abc <-- it's puts 'hoge'
  • 13. shebang and executable-file ● shebang ○ > vim hoge.sh #!/bin/sh <-- it's shebang liine echo $1 ● executable-file ○ set the executable flag > chmod +x hoge.sh ○ run > ./hoge.sh <-- don't forget path before filename! ■ hint: see the $PATH environment variable. it's search path for a command on your system. and think with a security policy.
  • 14. shebang for any script-files ● shell script #!/bin/sh ● node.js script #!/usr/bin/node ● python script #!/usr/bin/python ● php script #!/usr/bin/php ● haskell script #!/usr/bin/runhaskell hint: > file hoge.sh
  • 15. `for` statement and an array like variable # it's like an array separated by the space char values='aaa bbb ccc' # like the foreach in Java or for-in in JS for value in $values do echo $value done
  • 16. `seq` command > seq 8 1 2 3 4 5 6 7 8
  • 17. `...` <-- it's the back-quote pair, not a single-quote pair('...') # if use the single-quote pair > echo 'seq 512 64 768' seq 512 64 768 # if use the back-quote pair > echo `seq 512 64 768` 512 576 640 704 768 <-- it's like an array string the back-quote pattern is like an eval() in JS. it's run a text as a script code. be cautious!
  • 18. `for` statement with `seq` command and ` pattern it's give a loop with a numeric sequence. for value in `seq 0 15` do echo $value done
  • 19. `while` and `until` statements ● while <-- if true then loop while true do echo '\(^o^)/' done ● until <-- if false then loop until false do echo '/(^o^)\' done
  • 20. `test` command for comparison > test 3 -eq 4 <-- equiv (3 == 4) > echo $? 1 <-- so false in shell-script > test 3 -ne 4 <-- equiv (3 != 4) > echo $? 0 <-- so true in shell-script > test 3 -gt 4 <-- equiv (3 > 4) > echo $? 1 <-- so false in shell-script
  • 21. `test` command for file check > test -f /proc/cpuinfo <-- is the file available > echo $? 0 > test -d /boot <-- is the directory available > echo $? 0
  • 22. `expr` command for calc a number from a string # it's ng, not calc > echo 1 + 2 + 4 # it's ok, calc > echo `expr 1 + 2 + 4` 7 > expr 5 + ( 5 - 5 ) * 5 / 5 % 5 5 # note: ( ) * <-- need escape-sequence.
  • 23. `until` statement with `test`, `expr` and ` pattern it's give a loop with a numeric counter. counter=15 until `test $counter -eq 0` do echo $counter counter=`expr $counter - 1` done
  • 24. `if` statement # if.sh > source if.sh f(){ >f0 if test $1 -lt 0 then zero echo 'negative' >f1 elif test $1 -gt 0 positive then echo 'positive' > f -1 else negative echo 'zero' fi }
  • 25. `case` statement # case.sh > source case.sh f(){ >f0 case $1 in 0) zerp echo 'zero';; >f5 1) two-nine echo 'one';; [2-9]) > f -1 echo 'two-nine';; ???? default) echo '????' esac }
  • 26. where are more information? all of the information is available on the man pages. see the man pages. man page is the best unified answerer for all GNU/Linux users. > man sh