SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler offline
How to write a bash script like the python?




                Lloyd Huang
       KaLUG - Kaohsiung Linux User Group
             COSCUP Aug 18 2012
Before the start


Before the start
 • About Bash Python and me.

 • The ipython and lpython.py.
 • A trick, but it touches my heart.
  Examples of lpython.py :
    cat /etc/passwd | lpython.py 
    'for i in stdin:n s=i.split(":"); print s[0],s[5],s[6],'

    uname -a | lpython.py 'print stdin.read().split()[0:3]'




                                                                 2
Bash: Questions and answers


Bash: Questions and answers

   Q: How to be more logic and reuse?
   A: Function.
   Q: How to do unit testing?
   A: Function.
   Q: How different is between
      Bash function and Python module?
   A: ....




                                                 3
Bash source VS Python import


Bash source VS Python import
Python
 • A module allows you to logically organize your Python
    code. Grouping related code into a module makes the
    code easier to understand and use.
 • Python modules are easy to create; they're just files
    of Python program code.
 • if __name__ == '__main__':




                                                        4
Bash source VS Python import




How Bash do it?




                                  5
Bash source VS Python import


#!/bin/bash              | #!/usr/bin/python
funtest() {              | def funtest():
    echo "func for test" |     print "func for test"
}                        |
funfake() {              | def funfake():
    echo "func for fake" |     print "func for fake"
}                        |
# main                   | if __name__ == '__main__':
funtest                  |     funtest()
funfake                  |     funfake()

$> source samp00.sh      $> python
func for test            >>> import samp00
func for fake

$> bash samp00.sh        $> python samp00.py
func for test            func for test
func for fake            func for fake


                                                         6
Bash source VS Python import


#!/bin/bash                |   #!/usr/bin/python
funtest() {                |   def funtest():
    echo "func for test"   |       print "func for test"
}                          |
funfake() {                |   def funfake():
    echo "func for fake"   |       print "func for fake"
}                          |
return 2> /dev/null        |   if __name__ == '__main__':
funtest                    |       funtest()
funfake                    |       funfake()

$> source samp00.sh        $> python
                           >>> import samp00


$> bash samp00.sh          $> python samp00.py
func for test              func for test
func for fake              func for fake


                                                             7
Bash source VS Python import


#!/bin/bash
funtest() {
    echo "func for test"
}
funfake() {
    echo "func for fake"
}
if [ "$0" == "$BASH_SOURCE" ]; then
    funtest
    funfake
fi

                                             8
From xkcd http://xkcd.com/353/
Python module and docstring


Python module and docstring

    • import, from
    • import module as someone
       – Import module
    • del
       – Delete object
    • docstring
       – Python Documentation Strings



                                                 10
Python module and docstring


#!/usr/bin/python
def funtest():
    """
    Here is python docstring for funtest.
    Here is python docstring for funtest.
    """
    print "func for test"

def funfake():
    "Here is python docstring for funcfake."
    print "func for fake"

if __name__ == '__main__':
    funtest()
    funfake()

                                                     11
Python module and docstring


$> python
>>> import samp02
>>> samp02.
samp02.__doc__( samp02.funtest( samp02.funfake(

>>> samp02.funtest()
func for test

>>> help (samp02.funtest)
>>>
Help on function funtest in module samp02:

funtest()
  Here is python docstring for funtest.
  Here is python docstring for funtest.

                                                   12
Python module and docstring


>>> samp02.funfake.__doc__
'Here is python docstring for funcfake.'
>>> print samp02.funfake.__doc__
Here is python docstring for funcfake.

>>> import samp02 as new_samp02
>>> new_samp02.funtest()
func for test

>>> del new_samp02
>>> new_samp02.funtest()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  NameError: name 'new_samp' is not defined



                                                   13
Bash import and docstring ?


Bash import and docstring ?

Usage: source import.sh
    • import, from
    • import module as someone
      – Import module
    • del module
      – Delete module
    • help module.function
      – Documentation Strings

                                                  14
Bash import and docstring ?


#!/bin/bash
funtest() {
    __doc__="
Here is bash import.sh docstring for funtest
Here is bash import.sh docstring for funtest
"
    echo "func for test"
}
funfake() {
   __doc__="Here is bash import.sh docstring for funfake"
    echo "func for fake"
}
if [ "$0" == "$BASH_SOURCE" ]; then
    funtest
    funfake
fi



                                                        15
Bash import and docstring ?


$> source import.sh
$> import samp02.sh
$> samp02
samp02.funfake samp02.funtest
$> samp02.funtest
func for test
$> import samp02.sh as new_samp
$> new_samp.funtest
func for test
$> help new_samp.funtest
Here is bash import.sh docstring for funtest
Here is bash import.sh docstring for funtest

$> del new_samp
$> new_samp.funtest
bash: new_samp.funtest command not found



                                                       16
uid, gid = split(``1000:100'',``:'') ?


uid, gid = split(``1000:100'',``:'') ?
Python : split
    name, passwd, uid, gid, note, homedir, shell =
    string.split(www-data:x:33:33:www-data:/var/www:/bin/sh,:)


Bash : read
    LDread () {
     __doc__=LDread '.' 'V01.01.05.28.KH0.10.28' c1 c2 c3 c4 c5 c6 c7

        local ifs con
        ifs=$1; shift
        con=$1; shift
        IFS=$ifs read $@  (echo $con)
    }



                                                                     17
阿宅圖片來源:公立怪咖國民小學 http://blog.xuite.net/protion/school/9142122
Hook


Hook
   #!/bin/bash
   funtest() {
       __doc__=Hook test - Part I
   PreHook=echo This is PreHook
   PostHook=echo This is PostHook

       test -n $PreHook  $PreHook
       echo func for test
       test -n $PostHook  $PostHook
   }




                                            19
Hook


$ import hook00.sh
$ hook00.funtest
func for test

$ help hook00.funtest
Hook test - Part I
PreHook=echo This is PreHook
PostHook=echo This is PostHook

$ PreHook=echo This is PreHook
$ PostHook=echo This is PostHook
$ hook00.funtest
This is PreHook
func for test
This is PostHook

                                        20
Hook


#!/bin/bash
funtestPreHook () {
    return
}
funtestPostHook () {
    return
}
funtest() {
    __doc__=Hook test - Part II
funtestPreHook () { echo This is funtestPreHook; }
funtestPostHook () { echo This is funtestPostHook; } 

    funtestPreHook
    echo func for test
    funtestPostHook
}




                                                               21
Hook


$ import hook01.sh
$ hook01.funtest
func for test

$ help hook01.funtest
Hook test - Part II
hook01.funtestPreHook () { echo This is funtestPreHook; }
hook01.funtestPostHook () { echo This is funtestPostHook; }

$ hook01.funtestPreHook () { echo This is funtestPreHook; }
$ hook01.funtestPostHook () { echo This is funtestPostHook; }
$ hook01.funtest
This is funtestPreHook
func for test
This is funtestPostHook




                                                        22
Demo


Demo




         23
Advantages VS Problems


Advantages VS Problems
    • Advantages
      – Function reuse
      – Unit testing
      – Name space
      – Documentation strings
      – Grouping up commands
    • Problems
      – To Conflict with ImageMagick
      – Can't work with busybox ash



                                                 24

Mais conteúdo relacionado

Mais procurados

Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell ScriptingJaibeer Malik
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting BasicsSudharsan S
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting BasicsDr.Ravi
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell ScriptDr.Ravi
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scriptingvceder
 
Unix Basics
Unix BasicsUnix Basics
Unix BasicsDr.Ravi
 
Introduction to shell scripting
Introduction to shell scriptingIntroduction to shell scripting
Introduction to shell scriptingCorrado Santoro
 
Airlover 20030324 1
Airlover 20030324 1Airlover 20030324 1
Airlover 20030324 1Dr.Ravi
 
Linux shell env
Linux shell envLinux shell env
Linux shell envRahul Pola
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1Dr.Ravi
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Zyxware Technologies
 
Using Unix
Using UnixUsing Unix
Using UnixDr.Ravi
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scriptingAkshay Siwal
 
Shell programming 1.ppt
Shell programming  1.pptShell programming  1.ppt
Shell programming 1.pptKalkey
 

Mais procurados (20)

Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell Script
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scripting
 
Unix Basics
Unix BasicsUnix Basics
Unix Basics
 
Introduction to shell scripting
Introduction to shell scriptingIntroduction to shell scripting
Introduction to shell scripting
 
Chap06
Chap06Chap06
Chap06
 
Unix shell scripting
Unix shell scriptingUnix shell scripting
Unix shell scripting
 
Airlover 20030324 1
Airlover 20030324 1Airlover 20030324 1
Airlover 20030324 1
 
Linux shell env
Linux shell envLinux shell env
Linux shell env
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
 
Using Unix
Using UnixUsing Unix
Using Unix
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scripting
 
Scripting and the shell in LINUX
Scripting and the shell in LINUXScripting and the shell in LINUX
Scripting and the shell in LINUX
 
Shell programming 1.ppt
Shell programming  1.pptShell programming  1.ppt
Shell programming 1.ppt
 

Semelhante a COSCUP2012: How to write a bash script like the python?

Raspberry pi Part 25
Raspberry pi Part 25Raspberry pi Part 25
Raspberry pi Part 25Techvilla
 
Best training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingBest training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingvibrantuser
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...it-people
 
Best training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingBest training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingvibrantuser
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Samuel Lampa
 
Isolated development in python
Isolated development in pythonIsolated development in python
Isolated development in pythonAndrés J. Díaz
 
PM : code faster
PM : code fasterPM : code faster
PM : code fasterPHPPRO
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)James Titcumb
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserYodalee
 
Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)James Titcumb
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Module 03 Programming on Linux
Module 03 Programming on LinuxModule 03 Programming on Linux
Module 03 Programming on LinuxTushar B Kute
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)Olve Maudal
 
2-introduction_to_shell_scripting
2-introduction_to_shell_scripting2-introduction_to_shell_scripting
2-introduction_to_shell_scriptingerbipulkumar
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0Tim Bunce
 
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013Puppet
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyLarry Diehl
 

Semelhante a COSCUP2012: How to write a bash script like the python? (20)

Puppi. Puppet strings to the shell
Puppi. Puppet strings to the shellPuppi. Puppet strings to the shell
Puppi. Puppet strings to the shell
 
Raspberry pi Part 25
Raspberry pi Part 25Raspberry pi Part 25
Raspberry pi Part 25
 
Best training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingBest training-in-mumbai-shell scripting
Best training-in-mumbai-shell scripting
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
 
Best training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingBest training-in-mumbai-shell scripting
Best training-in-mumbai-shell scripting
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
Isolated development in python
Isolated development in pythonIsolated development in python
Isolated development in python
 
PM : code faster
PM : code fasterPM : code faster
PM : code faster
 
Metadata-driven Testing
Metadata-driven TestingMetadata-driven Testing
Metadata-driven Testing
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 
Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Module 03 Programming on Linux
Module 03 Programming on LinuxModule 03 Programming on Linux
Module 03 Programming on Linux
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
2-introduction_to_shell_scripting
2-introduction_to_shell_scripting2-introduction_to_shell_scripting
2-introduction_to_shell_scripting
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0
 
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
 

Último

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

COSCUP2012: How to write a bash script like the python?

  • 1. How to write a bash script like the python? Lloyd Huang KaLUG - Kaohsiung Linux User Group COSCUP Aug 18 2012
  • 2. Before the start Before the start • About Bash Python and me. • The ipython and lpython.py. • A trick, but it touches my heart. Examples of lpython.py : cat /etc/passwd | lpython.py 'for i in stdin:n s=i.split(":"); print s[0],s[5],s[6],' uname -a | lpython.py 'print stdin.read().split()[0:3]' 2
  • 3. Bash: Questions and answers Bash: Questions and answers Q: How to be more logic and reuse? A: Function. Q: How to do unit testing? A: Function. Q: How different is between Bash function and Python module? A: .... 3
  • 4. Bash source VS Python import Bash source VS Python import Python • A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. • Python modules are easy to create; they're just files of Python program code. • if __name__ == '__main__': 4
  • 5. Bash source VS Python import How Bash do it? 5
  • 6. Bash source VS Python import #!/bin/bash | #!/usr/bin/python funtest() { | def funtest(): echo "func for test" | print "func for test" } | funfake() { | def funfake(): echo "func for fake" | print "func for fake" } | # main | if __name__ == '__main__': funtest | funtest() funfake | funfake() $> source samp00.sh $> python func for test >>> import samp00 func for fake $> bash samp00.sh $> python samp00.py func for test func for test func for fake func for fake 6
  • 7. Bash source VS Python import #!/bin/bash | #!/usr/bin/python funtest() { | def funtest(): echo "func for test" | print "func for test" } | funfake() { | def funfake(): echo "func for fake" | print "func for fake" } | return 2> /dev/null | if __name__ == '__main__': funtest | funtest() funfake | funfake() $> source samp00.sh $> python >>> import samp00 $> bash samp00.sh $> python samp00.py func for test func for test func for fake func for fake 7
  • 8. Bash source VS Python import #!/bin/bash funtest() { echo "func for test" } funfake() { echo "func for fake" } if [ "$0" == "$BASH_SOURCE" ]; then funtest funfake fi 8
  • 10. Python module and docstring Python module and docstring • import, from • import module as someone – Import module • del – Delete object • docstring – Python Documentation Strings 10
  • 11. Python module and docstring #!/usr/bin/python def funtest(): """ Here is python docstring for funtest. Here is python docstring for funtest. """ print "func for test" def funfake(): "Here is python docstring for funcfake." print "func for fake" if __name__ == '__main__': funtest() funfake() 11
  • 12. Python module and docstring $> python >>> import samp02 >>> samp02. samp02.__doc__( samp02.funtest( samp02.funfake( >>> samp02.funtest() func for test >>> help (samp02.funtest) >>> Help on function funtest in module samp02: funtest() Here is python docstring for funtest. Here is python docstring for funtest. 12
  • 13. Python module and docstring >>> samp02.funfake.__doc__ 'Here is python docstring for funcfake.' >>> print samp02.funfake.__doc__ Here is python docstring for funcfake. >>> import samp02 as new_samp02 >>> new_samp02.funtest() func for test >>> del new_samp02 >>> new_samp02.funtest() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'new_samp' is not defined 13
  • 14. Bash import and docstring ? Bash import and docstring ? Usage: source import.sh • import, from • import module as someone – Import module • del module – Delete module • help module.function – Documentation Strings 14
  • 15. Bash import and docstring ? #!/bin/bash funtest() { __doc__=" Here is bash import.sh docstring for funtest Here is bash import.sh docstring for funtest " echo "func for test" } funfake() { __doc__="Here is bash import.sh docstring for funfake" echo "func for fake" } if [ "$0" == "$BASH_SOURCE" ]; then funtest funfake fi 15
  • 16. Bash import and docstring ? $> source import.sh $> import samp02.sh $> samp02 samp02.funfake samp02.funtest $> samp02.funtest func for test $> import samp02.sh as new_samp $> new_samp.funtest func for test $> help new_samp.funtest Here is bash import.sh docstring for funtest Here is bash import.sh docstring for funtest $> del new_samp $> new_samp.funtest bash: new_samp.funtest command not found 16
  • 17. uid, gid = split(``1000:100'',``:'') ? uid, gid = split(``1000:100'',``:'') ? Python : split name, passwd, uid, gid, note, homedir, shell = string.split(www-data:x:33:33:www-data:/var/www:/bin/sh,:) Bash : read LDread () { __doc__=LDread '.' 'V01.01.05.28.KH0.10.28' c1 c2 c3 c4 c5 c6 c7 local ifs con ifs=$1; shift con=$1; shift IFS=$ifs read $@ (echo $con) } 17
  • 19. Hook Hook #!/bin/bash funtest() { __doc__=Hook test - Part I PreHook=echo This is PreHook PostHook=echo This is PostHook test -n $PreHook $PreHook echo func for test test -n $PostHook $PostHook } 19
  • 20. Hook $ import hook00.sh $ hook00.funtest func for test $ help hook00.funtest Hook test - Part I PreHook=echo This is PreHook PostHook=echo This is PostHook $ PreHook=echo This is PreHook $ PostHook=echo This is PostHook $ hook00.funtest This is PreHook func for test This is PostHook 20
  • 21. Hook #!/bin/bash funtestPreHook () { return } funtestPostHook () { return } funtest() { __doc__=Hook test - Part II funtestPreHook () { echo This is funtestPreHook; } funtestPostHook () { echo This is funtestPostHook; } funtestPreHook echo func for test funtestPostHook } 21
  • 22. Hook $ import hook01.sh $ hook01.funtest func for test $ help hook01.funtest Hook test - Part II hook01.funtestPreHook () { echo This is funtestPreHook; } hook01.funtestPostHook () { echo This is funtestPostHook; } $ hook01.funtestPreHook () { echo This is funtestPreHook; } $ hook01.funtestPostHook () { echo This is funtestPostHook; } $ hook01.funtest This is funtestPreHook func for test This is funtestPostHook 22
  • 23. Demo Demo 23
  • 24. Advantages VS Problems Advantages VS Problems • Advantages – Function reuse – Unit testing – Name space – Documentation strings – Grouping up commands • Problems – To Conflict with ImageMagick – Can't work with busybox ash 24