SlideShare a Scribd company logo
1 of 230
Download to read offline
Don’t be a rookie forever.
      Be in command! (line)




                 Giuseppe Maxia
                 @datacharmer
                                                                             $
       This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License.
Sunday, August 21, 11
about me -Giuseppe Maxia
   §    a.k.a. The Data Charmer
   §    QA Director, Continuent, Inc
   §    Long time hacking with database features
   §    Formerly, database consultant, designer, coder.
   §    A passion for QA
   §    An even greater passion for open source
   §    ... and community
   §    Passionate blogger
   §    http://datacharmer.blogspot.com




Sunday, August 21, 11
What this tutorial is about
   § Providing tools and tips for command line users;
   § Learn a few tricks to make you achieve more and type
      less.




Sunday, August 21, 11
What this tutorial is about
   § Providing tools and tips for command line users;
   § Learn a few tricks to make you achieve more and type
      less.
   § Making GUI enthusiasts green with envy;
                                  bar

                          foo
                                         baz




Sunday, August 21, 11
This tutorial
   §    A quick guide at the command line usage
   §    A practical case for database admins
   §    but ...
   §    Useful for all




Sunday, August 21, 11
Problem
   § One document contains one date in 'mm/dd/yyyy'
      format
   § Need to convert the date into the 'yyyy-mm-dd' format
      (or dd.mm.yyyy)

      GUI USER SOLUTION
   § open the document with a word processor
   § change the date

   § Command line USER SOLUTION
   § Probably the same


Sunday, August 21, 11
Problem
   § One document contains many dates in 'mm/dd/yyyy'
      format
   § Need to convert the dates into the 'yyyy-mm-dd'
      format (or dd.mm.yyyy)

      GUI USER SOLUTION
   § open the document with an advanced word processor
   § hope it supports regular expressions

   § Command line USER SOLUTION
   § Use vi or emacs. Do a search-and-replace operation
   § Or use the next page solution
Sunday, August 21, 11
Problem
   § Many documents contain many dates in 'mm/dd/yyyy'
      format
   § Need to convert the dates in all documents into the
      'yyyy-mm-dd' format (or dd.mm.yyyy)

      GUI USER SOLUTION
   § Realizes that it will take days to do this manually
   § Scream

   § Command Line USER SOLUTION
   § uses sed or perl to do the replacement in one line


Sunday, August 21, 11
the command line



                ?
                        WHY
                              8


Sunday, August 21, 11
An educational story
        1985-90
        1991
        1993
        1994
        1995-97
        1998-99
        2000-2001
        2001-2006
        2007-2009
        2010-
                          9


Sunday, August 21, 11
An educational story
        1985-90         • MS-DOS
        1991
        1993
        1994
        1995-97
        1998-99
        2000-2001
        2001-2006
        2007-2009
        2010-
                                   9


Sunday, August 21, 11
An educational story
        1985-90         • MS-DOS
        1991            • Windows 3.0
        1993
        1994
        1995-97
        1998-99
        2000-2001
        2001-2006
        2007-2009
        2010-
                                        9


Sunday, August 21, 11
An educational story
        1985-90         • MS-DOS
        1991            • Windows 3.0
        1993            • Windows 3.1
        1994
        1995-97
        1998-99
        2000-2001
        2001-2006
        2007-2009
        2010-
                                        9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS
        1991            •   Windows 3.0
        1993            •   Windows 3.1
        1994            •   Windows NT
        1995-97
        1998-99
        2000-2001
        2001-2006
        2007-2009
        2010-
                                          9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS
        1991            •   Windows 3.0
        1993            •   Windows 3.1
        1994            •   Windows NT
        1995-97         •   Windows 95
        1998-99
        2000-2001
        2001-2006
        2007-2009
        2010-
                                          9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS
        1991            •   Windows 3.0
        1993            •   Windows 3.1
        1994            •   Windows NT
        1995-97         •   Windows 95
        1998-99         •   Windows 98
        2000-2001
        2001-2006
        2007-2009
        2010-
                                          9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS
        1991            •   Windows 3.0
        1993            •   Windows 3.1
        1994            •   Windows NT
        1995-97         •   Windows 95
        1998-99         •   Windows 98
        2000-2001       •   Windows 2000
        2001-2006
        2007-2009
        2010-
                                           9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS
        1991            •   Windows 3.0
        1993            •   Windows 3.1
        1994            •   Windows NT
        1995-97         •   Windows 95
        1998-99         •   Windows 98
        2000-2001       •   Windows 2000
        2001-2006       •   Windows XP
        2007-2009
        2010-
                                           9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS
        1991            •   Windows 3.0
        1993            •   Windows 3.1
        1994            •   Windows NT
        1995-97         •   Windows 95
        1998-99         •   Windows 98
        2000-2001       •   Windows 2000
        2001-2006       •   Windows XP
        2007-2009       •   Windows Vista
        2010-
                                            9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS
        1991            •   Windows 3.0
        1993            •   Windows 3.1
        1994            •   Windows NT
        1995-97         •   Windows 95
        1998-99         •   Windows 98
        2000-2001       •   Windows 2000
        2001-2006       •   Windows XP
        2007-2009       •   Windows Vista
        2010-           •   Windows 7
                                            9


Sunday, August 21, 11
An educational story
        1985-90         •   MS-DOS        • Unix shell
        1991            •   Windows 3.0
        1993            •   Windows 3.1 • Linux
        1994            •   Windows NT
        1995-97         •   Windows 95
        1998-99         •   Windows 98
        2000-2001       •   Windows 2000
        2001-2006       •   Windows XP    • Mac OSX
        2007-2009       •   Windows Vista
        2010-           •   Windows 7
                                                  9


Sunday, August 21, 11
Why the command line
      • portability
      • efficiency
      • fun




                           10


Sunday, August 21, 11
the command line (for rookies)


            ||||
                         NO
                        PANIC        11


Sunday, August 21, 11
Command line panic (for rookies)




                        $_
Sunday, August 21, 11
Command line panic (for rookies)




                        $_
               NOW WHAT?
Sunday, August 21, 11
the command line (for rookies)



                        BASICS
                                     13


Sunday, August 21, 11
The shell
      • It's a command interpreter
      • There are many flavors
          > bash
          > zsh
          > ksh




                                     14


Sunday, August 21, 11
MySQL command line client
      • called "mysql"
          > Takes SQL commands
          > sends them to the server
          > gets results


      • but it can do much more ...




                                       15


Sunday, August 21, 11
other tools
      •   Shell scripts
      •   Aliases
      •   Perl
      •   awk
      •   sort
      •    …. and a lot of Unix little helper



                                                16


Sunday, August 21, 11
other tools
      •   Shell scripts
      •   Aliases
      •   Perl          which could replace everything else, of course
      •   awk
      •   sort
      •    …. and a lot of Unix little helper



                                                                     16


Sunday, August 21, 11
in case it wasn't clear (yeah, for
                                  rookies)




                                    17


Sunday, August 21, 11
in case it wasn't clear (yeah, for
                                  rookies)
      • command line actions are




                                    17


Sunday, August 21, 11
in case it wasn't clear (yeah, for
                                  rookies)
      • command line actions are
          > commands (the name of the application to invoke)




                                                               17


Sunday, August 21, 11
in case it wasn't clear (yeah, for
                                  rookies)
      • command line actions are
          > commands (the name of the application to invoke)
          > parameters (optional arguments for the application)




                                                                  17


Sunday, August 21, 11
in case it wasn't clear (yeah, for
                                  rookies)
      • command line actions are
          > commands (the name of the application to invoke)
          > parameters (optional arguments for the application)
          > and the ENTER key




                                                                  17


Sunday, August 21, 11
in case it wasn't clear (yeah, for
                                  rookies)
      • command line actions are
          > commands (the name of the application to invoke)
          > parameters (optional arguments for the application)
          > and the ENTER key


                                         Enter

                                                                  17


Sunday, August 21, 11
The Unix philosophy (1)
      • One tool for every feature
          > make one tool that does one thing well
          > for many features, make many tools
          > make them work together (see next slide)




                                                       18


Sunday, August 21, 11
The Unix philosophy (2)
    • To make several tool cooperate:
          > pipe the output of one tool to the input of another one.
          > for more actions, pipe more tools


        $ sort < filename | uniq | nl




                                                                  19


Sunday, August 21, 11
Unix pipes




                        20


Sunday, August 21, 11
Unix pipes

              application   <   input




                                        20


Sunday, August 21, 11
Unix pipes

              application   <   input

              application   >   output




                                         20


Sunday, August 21, 11
Unix pipes

              application   <   input

              application   >   output


              application   <   input    >   output




                                                      20


Sunday, August 21, 11
Unix pipes

              application   <   input

              application   >   output


              application   <   input    >   output



              application   |       application


                                                      20


Sunday, August 21, 11
Unix pipes

              application        <   input

              application        >   output


              application        <   input        >   output



              application        |           application


                        output       input
                                                               20


Sunday, August 21, 11
Unix pipes = parallel processing




                                   21


Sunday, August 21, 11
Unix pipes = parallel processing

            application   |   application




                                            21


Sunday, August 21, 11
Unix pipes = parallel processing

            application   |   application




                                            21


Sunday, August 21, 11
Unix pipes = parallel processing

            application   |   application

              output




                                            21


Sunday, August 21, 11
Unix pipes = parallel processing

            application   |     application

              output          input




                                              21


Sunday, August 21, 11
Unix pipes = parallel processing

            application   |     application

              output          input




                                              21


Sunday, August 21, 11
Unix pipes = parallel processing

            application   |     application

              output          input




                                              21


Sunday, August 21, 11
Unix pipes = parallel processing

            application   |     application

              output          input




                                              21


Sunday, August 21, 11
Who gets what
      •   shell
      •   application
      •   database server
      •   pager




                            22


Sunday, August 21, 11
who gets what


            shell prompt
            $ mysql



                           mysql client




                                          mysql server
                                                         23


Sunday, August 21, 11
who gets what
                                       any host   mysql server




            shell
                        mysql client




                                                                 24


Sunday, August 21, 11
who gets what
$ mysql -u username -ppassword




                        First the application
                        then the server




                                                25


Sunday, August 21, 11
who gets what
$ mysql -u username -ppassword 
  -e "select VERSION()"



                                goes to the client, then the
                                server

           goes to the server




                                                               26


Sunday, August 21, 11
who gets what
mysql> help
mysql> pager less                            goes to the client only
mysql> select 1;




                        goes to the server




                                                                27


Sunday, August 21, 11
the command line




      readline
                        28


Sunday, August 21, 11
readline
      • Common component
          > shell
          > mysql client
          > many CLI applications




                                    29


Sunday, August 21, 11
Main cursor movements
            Ctrl A      Start/End of line
            Ctrl E
            Meta B      Back/Forward one word
            Meta F
                        previous/next command

            Ctrl L      clear screen and take
                        current line on top
            Ctrl R      Search history
                                                30


Sunday, August 21, 11
Changing text
            Meta U           Uppercase word
            Meta L           Lowercase word
            Ctrl D           delete word
            Ctrl K           delete to end of line
            Ctrl -           undo

                        for more tips:
                        $ man readline               31


Sunday, August 21, 11
Some conventions in this talk
$ command
at the shell

mysql> command
at the mysql prompt




                                    32


Sunday, August 21, 11
The command line friends



                        #!
                             handy
Sunday, August 21, 11
                             tools
                                33
your best friends at the command line
      •   man
      •   ls
      •   cd
      •   find
      •   grep
      •   date
      •   echo
      •   pwd
      •   mv
                                34
      •   cp
Sunday, August 21, 11
man {command_name}
    • Tells you how to use a command

        man ls




                                       35


Sunday, August 21, 11
ls [directory]
    • lists contents of current [or given] directory


        ls

        ls /some/path

        ls *.txt

                                                       36


Sunday, August 21, 11
cd [directory]
    • change directory to given path
    • takes to $HOME directory if no path is given


        cd /some/path

        cd ..


                                                     37


Sunday, August 21, 11
find {directory} [conditions]
    • finds files in the given directory that satisfy conditions

        find $HOME/docs -name "*mouse*"




                                                           38


Sunday, August 21, 11
grep {pattern} filename
    • finds pattern matching rows in filename

        grep Munich *.txt

        grep "Munich|Berlin" *.txt

        grep "[0-9][0-9]:[0-9][0-9]" a.txt


                                                39


Sunday, August 21, 11
date [layout]
    • displays the current date and time, with optional layout

        date
        Tue Aug 16 08:33:04 CEST 2011

        date '+%Y-%m-%d'
        2011-08-16


                                                        40


Sunday, August 21, 11
echo "message"
    • displays the given message and/or variables

        echo "hi"
        hi

        GREETINGS='Hello, there!'
        echo $GREETINGS
        Hello, there!

                                                    41


Sunday, August 21, 11
pwd
    • displays the current path (Print Working Directory

        pwd
        /home/gmax/test_dir




                                                       42


Sunday, August 21, 11
mv old_file_name new_file_name
    • moves a file from one place to another
    • renames a file

        mv ugly.txt /some/other/path
        mv *.txt /storage/texts

        mv ugly.txt beautiful.txt


                                               43


Sunday, August 21, 11
cp file_name destination
    • copies a file from one place to another
    • creates a copy of a file

        cp ugly.txt /some/other/path
        cp *.txt /storage/texts

        cp ugly.txt beautiful.txt


                                                44


Sunday, August 21, 11
other important friends at the
 command line
      •   rm
      •   mkdir
      •   rmdir
      •   cat
      •   sed
      •   strings
      •   wc
      •   head
      •   tail
      •   more/less               45

      •   sort
Sunday, August 21, 11
rm file_name
    • removes a file

        rm ugly.txt
        rm *.txt

        ### DANGER!!!!
        rm -r *
        rm -rf *

                         46


Sunday, August 21, 11
mkdir/rmdir directory
    • creates or removes a directory

        mkdir mydir

        rmdir mydir




                                       47


Sunday, August 21, 11
cat
    • shows the contents of a file

        cat addresses.txt




                                     48


Sunday, August 21, 11
sed [option] file
    • performs editing on a file

        sed -e 's/Ship/Airplane/' travel.txt




                                     49


Sunday, August 21, 11
strings filename
    • extracts printable text from a file

        strings /bin/ls




                                            50


Sunday, August 21, 11
wc filename
    • counts words (and characters and lines) in a file

        wc .bashrc
              72     164    2842 .bashrc
        # (lines, words, characters)




                                                          51


Sunday, August 21, 11
head/tail filename
    • display the first or the last lines of a file

        head long_file.txt
        head -n 5 long_file.txt

        tail long_file.txt
        tail -n 1 long_file.txt


                                                      52


Sunday, August 21, 11
more/less filename
    • display a file with scrollable pages

        # old: inefficient
        more filename.txt

        # new: preferred
        less filename.txt


                                             53


Sunday, August 21, 11
sort filename
    • displays the ordered contents of a filename

        sort unordered.txt

        sort unordered.txt > sorted.txt




                                                    54


Sunday, August 21, 11
#!
                          mixing
                         languages
                                55


Sunday, August 21, 11
This is a story about
            languages

Sunday, August 21, 11
you got to understand,
                        Bernie, it's not personal.
                          It's just that you are
                                 obsolete
We use
language
to talk to
computers



Sunday, August 21, 11
10 print "hello"
We use                  20 goto 10
languages
to talk to
computers



Sunday, August 21, 11
I am a polyglot



Sunday, August 21, 11
An imperfect
                polyglot, actually


Sunday, August 21, 11
I speak
   Italian




Sunday, August 21, 11
I speak
   Italian


       with a clear
        Sardinian
         accent

Sunday, August 21, 11
I speak
   English




Sunday, August 21, 11
I speak
   English


     with a distinct
     Italian accent

Sunday, August 21, 11
I speak
   Perl




Sunday, August 21, 11
I speak
   Perl


  with a hint of a C
        accent

Sunday, August 21, 11
I speak
   French
   and
   Spanish




Sunday, August 21, 11
I speak
   French
   and
   Spanish
   but since I use
  them very little,
 they have melted
  with Italian and
       English
Sunday, August 21, 11
I speak
                        #!/bin/bash
   Bash




Sunday, August 21, 11
I speak
                        #!/bin/bash
   Bash


      with a strong
       Perl accent

Sunday, August 21, 11
I speak fluent Italian

                        La donzelletta vien dalla
                        campagna, in sul calar del
                        sole, col suo fascio dell'erba
                        e reca in mano un mazzolino
                        di rose e viole, onde, siccome
                        suole, ornare ella si appresta ...




Sunday, August 21, 11
However, Sardinian comes handy sometimes




                          Maissavida
                          ti frimisti! (*)




                              (*) May you never stop
Sunday, August 21, 11
I speak fluent English


                        When in the Course of human events, it becomes
                        necessary for one people to dissolve the political bands
                        which have connected them with another, and to assume
                        among the powers of the earth, the separate and equal
                        station to which the Laws of Nature and of Nature's God
                        entitle them, a decent respect to the opinions of mankind
                        requires that they should declare the causes which impel
                        them to the separation.




Sunday, August 21, 11
I speak fluent English


                        When in the Course of human events, it becomes
                        necessary for one people to dissolve the political bands
                        which have connected them with another, and to assume
                        among the powers of the earth, the separate and equal
                        station to which the Laws of Nature and of Nature's God
                        entitle them, a decent respect to the opinions of mankind
                        requires that they should declare the causes which impel
                        them to the separation.



                                                                        hmm.
                                                                        wrong
                                                                        flag

Sunday, August 21, 11
I speak fluent English


                        When in the Course of human events, it becomes
                        necessary for one people to dissolve the political bands
                        which have connected them with another, and to assume
                        among the powers of the earth, the separate and equal
                        station to which the Laws of Nature and of Nature's God
                        entitle them, a decent respect to the opinions of mankind
                        requires that they should declare the causes which impel
                        them to the separation.




Sunday, August 21, 11
But sometimes Italian is still necessary


                                 barista al fresco pasta
                             maestro        espresso      tempo
                        vendetta        soprano finale          piano
                         dilettante cappuccino           stucco
                        stiletto virtuoso fiasco presto lotto
                             pizza      bravo             lasagna
                                 studio        spaghetti
                                         stanza




Sunday, August 21, 11
And sometimes Italian is needed




                           I tuoi perversi
                           defunti!(*)




                           (*) Your wicked ancestors!
Sunday, August 21, 11
Although Sardinian is still effective here




                              Ancu ti currullidi
                              sa giustizia (*)




                          (*) May the rule of law chase you
Sunday, August 21, 11
I speak Perl fluently

                        #!/usr/bin/perl
                        use strict;
                        use warnings;
                        use File::Find;

                        while (my $line = <stdin>){
                          # …




Sunday, August 21, 11
Sometimes, I need help from C

                        use Inline C;
                        print "9 + 16 = ", add(9, 16), "n";

                        __END__
                        __C__
                        int add(int x, int y) {
                              return x + y;
                        }




Sunday, August 21, 11
Most of my work at the command line is Bash


                        $ for D in $HOME/*/; do du -sh $D;
                        > done > /tmp/occupancy




                                            #!/bin/bash
Sunday, August 21, 11
And sometimes, a pinch of Perl can help


                 $ perl -pe
                 's{(dd)-(dd)-(dddd)}{$3-$1-$2}g' 
                  < rawfile.txt > betterfile.txt




                                       #!/bin/bash
Sunday, August 21, 11
And then on top of all this, I need to speak SQL


                 $ mysql -e
                 'SELECT COUNT(*) FROM dbname.tbl_name
                 WHERE col_name = 1 and other_col="A" '




Sunday, August 21, 11
I wish I could say that my SQL has a Perlish
   accent


                        $ mysql -e
                        'SELECT COUNT(*) FROM dbname.tbl_name
                        WHERE col_name = 1 and other_col="A" '

                           use strict;
                           use DBI;?




Sunday, August 21, 11
I wish I could say that my SQL has a Perlish
   accent


                        $ mysql -e
                        'SELECT COUNT(*) FROM dbname.tbl_name
                        WHERE col_name = 1 and other_col="A" '



                  but it wouldn't be true




Sunday, August 21, 11
I could curse in Perl




                           $ perl -pe
                           's{(dd)-(dd)-(ddd
                           d)}{$3-$1-$2}g' 
                            < rawfile.txt >
                           betterfile.txt (*)




   But it would not
   get me far.
                            (*) already translated
Sunday, August 21, 11
Then




Sunday, August 21, 11
Then


    I will need to mix languages.




Sunday, August 21, 11
Then


    I will need to mix languages.


                        This talk will show exactly that.




Sunday, August 21, 11
Then


    I will need to mix languages.


                        This talk will show exactly that.


        Mixing languages.




Sunday, August 21, 11
Then


    I will need to mix languages.


                        This talk will show exactly that.


        Mixing languages.
                                           Yes.



Sunday, August 21, 11
Then


    I will need to mix languages.


                        This talk will show exactly that.


        Mixing languages.
                                           Yes.

                                $ at the command line
Sunday, August 21, 11
the Bash shell



                    #!
                         bash
                            81


Sunday, August 21, 11
components
      •   commands
      •   aliases
      •   variables
      •   functions




                        82


Sunday, August 21, 11
commands
$ echo "something"
something




                        83


Sunday, August 21, 11
aliases
$ alias mydate='mysql -e "select NOW()"'
$ mydate
+---------------------+
| now()               |
+---------------------+
| 2010-04-12 07:14:19 |
+---------------------+




                                 84


Sunday, August 21, 11
aliases
$ alias myself='mysql'
$ myself -e "select NOW()"'
+---------------------+
| now()                |
+---------------------+
| 2010-04-12 07:14:19 |
+---------------------+




                              85


Sunday, August 21, 11
variables
$ MYBATCH='mysql -N -B'
$ MYQUERY='select curdate()'
$ $MYBATCH -e "$MYQUERY"
2010-04-12




                               86


Sunday, August 21, 11
nesting variables
# t.sh
 CMD="SELECT TABLE_NAME"
 TBL='information_schema.tables'
 WHC1="TABLE_SCHEMA='mysql'"
 WHC2="TABLE_NAME like 'u%' "
 Q1="$CMD FROM $TBL"
 Q2="WHERE $WHC1 AND $WHC2"
 Q="$Q1 $Q2"
 echo $Q
 echo $Q | mysql
                                   87


Sunday, August 21, 11
nesting variables
$ sh t.sh
SELECT TABLE_NAME FROM
information_schema.tables WHERE
TABLE_SCHEMA='mysql' AND TABLE_NAME like
'u%'
TABLE_NAME
user




                                 88


Sunday, August 21, 11
the mysql command line client



                        mysql>

                                    89


Sunday, August 21, 11
SQL commands from a file
   $ mysql < filename.sql
   mysql> source filename.sql

   • executes the commands contained in
     filename.sql
   • commands can be queries understood
     by the server
   • and commands for the client


                                  90


Sunday, August 21, 11
SQL commands at the command line
   $ application | mysql
   $ echo "SELECT 1" | mysql
   $ mysql -e "SELECT 1"

   • executes the commands from standard
     input
   • commands can be queries understood
     by the server
   • and commands for the client

                                  91


Sunday, August 21, 11
batch mode
   $ echo "select curdate()" | mysql
   curdate()
   2010-04-12




                                 92


Sunday, August 21, 11
table mode
   $ echo "select curdate()" | mysql -t
   +------------+
   | curdate() |
   +------------+
   | 2010-04-12 |
   +------------+




                                 93


Sunday, August 21, 11
table mode
   $ mysql -e "select curdate()"
   +------------+
   | curdate() |
   +------------+
   | 2010-04-12 |
   +------------+




                                   94


Sunday, August 21, 11
Forcing batch mode
   mysql -B -e 'select curdate()'
   curdate()
   2010-04-12




                                    95


Sunday, August 21, 11
Forcing batch mode - no header
   mysql -N -B -e 'select curdate()'
   2010-04-12




                                  ANT!
                             PO RT
                        IM

                                         96


Sunday, August 21, 11
Shell + mysql
   $ echo "The current server's date is
   `mysql -N -B -e 'select curdate()'`."

   $ echo "The current server's date is
   $(mysql -N -B -e 'select
   curdate()')."




                                 97


Sunday, August 21, 11
advanced command line techniques
               ((((((
               (:
           @            @
                -


               $_




                            loops
                                98


Sunday, August 21, 11
loops basics
   $      for N in 1 2 3
   >      do
   >      echo $N
   >      done
   1
   2
   3



                           99


Sunday, August 21, 11
loops basics
   $ for N in 1 2 3 ; do echo $N ; done
   1
   2
   3




                                 100


Sunday, August 21, 11
loops basics
   $ for N in $(seq 1 3) ;
    do echo "this is number $N" ;
    done

   this is number 1
   this is number 2
   this is number 3



                                 101


Sunday, August 21, 11
loops from file
   $ head /usr/share/dict/words
   A
   a
   aa
   aal
   aalii
   aam
   Aani
   aardvark
   aardwolf
                                  102


Sunday, August 21, 11
loops from file
   $ for U in 
   $(head /usr/share/dict/words ) ; do
   perl -le 'print uc shift' $U ; done
   A
   A
   AA
   AAL
   AALII
   AAM
   AANI
                                 103


Sunday, August 21, 11
loops from mysql results
   $ mysql -B -N -e 'show tables from
   world'
   City
   Country
   CountryLanguage




                                104


Sunday, August 21, 11
loops from mysql results
   $ for T in $(mysql -B -N -e 'show
   tables from world') ;
   >    do echo "CREATE TABLE world2.$T
   LIKE world.$T;" ; done

   CREATE TABLE world2.City LIKE
   world.City;
   CREATE TABLE world2.Country LIKE
   world.Country;
   CREATE TABLE world2.CountryLanguage
   LIKE world.CountryLanguage;
                                 105


Sunday, August 21, 11
piping loops back into mysql
   $ for T in $(mysql -B -N -e 'show
   tables from world') ;
   >    do echo "CREATE TABLE world2.$T
   LIKE world.$T;" ; done 
   > | mysql -vv




                                   106


Sunday, August 21, 11
advanced command line techniques



              nested

                                      :)
                                 @         @




                                       -
                                      $_

                        #!
                        #!
                         #!
                         #!



                  loops
                          #!
                           #!




                                107


Sunday, August 21, 11
doing something for every table
    in every database
   $ mysql -e "show databases"
   +--------------------+
   | Database           |
   +--------------------+
   | information_schema |
   | mysql              |
   | sakila             |
   | world              |
   +--------------------+
                                  108


Sunday, August 21, 11
doing something for every table
    in every database
   $ mysql -e "show tables from world"
   +-----------------+
   | Tables_in_world |
   +-----------------+
   | City            |
   | Country         |
   | CountryLanguage |
   +-----------------+

                                  109


Sunday, August 21, 11
pseudocode
for each database
  do
  for each table
     do
     print the table name




                            110


Sunday, August 21, 11
actual code
alias mybatch='mysql -B -N'
for D in $(mybatch -e "SHOW SCHEMAS")
do
   for T in 
   $(mybatch -e "SHOW TABLES FROM $D")
   do
      echo "$D.$T"
   done
done

                                111


Sunday, August 21, 11
advanced command line techniques
                           $HOME




     options
      files                        112


Sunday, August 21, 11
Default option files
/etc/my.cnf
/etc/mysql/my.cnf (Debian, Ubuntu)
$BASEDIR/my.cnf
$HOME/.my.cnf




                               113


Sunday, August 21, 11
Custom option files
$ mysql --no-defaults
$ mysql --defaults-file=filename
$ mysql --defaults-extra-file=filename




                               114


Sunday, August 21, 11
Option files sections
[mysqld]
# option for server

[client]
# option for any mysql client

[mysql]
# options specific to 'mysql' CLI app


                                115


Sunday, August 21, 11
Option files example

[client]
user=myname
password=mypassword

[mysql]
prompt="mysql (h) {u} [d] > "



                               116


Sunday, August 21, 11
Option files: caution
# protect your option files!

$ chmod 600 $HOME/.my.cnf

$ ls -l .my.cnf
-rw------- 1 [...] 10:04 .my.cnf




                               117


Sunday, August 21, 11
prompt
mysql> prompt gm (h) {u} [d] >
PROMPT set to 'gm (h) {u} [d] > '
gm (localhost) {root} [(none)] > use test
Database changed
gm (localhost) {root} [test] >

# h -> host
# u -> user
# d -> database

                                 118


Sunday, August 21, 11
advanced command line techniques
            ((((((
            (:

        @            @
             -




            #!




                         aliases
                               119


Sunday, August 21, 11
An useful alias
$ alias mysql_as_root=
'mysql --
defaults_file=~/.my_as_root.cnf'

mysql_as_root -e "select user()"
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
                               120


Sunday, August 21, 11
An useful alias
#.my_as_root.cnf'
[client]
user=root
password=your_mysql_root_password

[mysql]
prompt="### [h] {u} (d) > "



                                 121


Sunday, August 21, 11
Another useful alias
alias mybatch='mysql -B -N '


mybatch -e "select version()"
5.1.45-log




                                122


Sunday, August 21, 11
( )
    advanced command line techniques
                   ((((((
                   (:
               @            @
                   -



                   #!




   functions
                                123


Sunday, August 21, 11
functions
      • like aliases, but with parameters




                                            124


Sunday, August 21, 11
sample function
function grant_new {
    mysql_as_root -e 
    "GRANT $1 on $2 to $3 identified
by "$4" "
}


$ grant_new SELECT "world.*" john 
  john_secret

                               125


Sunday, August 21, 11
sample function
$ mysql_as_root 
  -e 'show grants for johnG'
*** 1. row ***
Grants for john@%: GRANT USAGE ON *.*
TO 'john'@'%' IDENTIFIED BY PASSWORD
'*73A88CE13374128844E3ABB500F439A9C02C
53A3'
*** 2. row ***
Grants for john@%: GRANT SELECT ON
`world`.* TO 'john'@'%'

                               126


Sunday, August 21, 11
advanced command line techniques



             $_         getting
                         query
                        details127


Sunday, August 21, 11
which query is being executed?
# wrong.sql
# this script has one error
use test ;
drop table if exists t1 ;
create table t1 (id int);
insert into t1 values (a);




                                 128


Sunday, August 21, 11
which query is being executed?
$ mysql < wrong.sql
ERROR 1054 (42S22) at line 4: Unknown
column 'a' in 'field list'


# WHERE IS THE ERROR?




                                 129


Sunday, August 21, 11
which query is being executed?
$ mysql -v < wrong.sql
--------------
drop table if exists t1
--------------
--------------
create table t1 (id int)
--------------
--------------
insert into t1 values (a)
--------------
ERROR 1054 (42S22) at line 4: Unknown column
'a' in 'field list'
                                      130


Sunday, August 21, 11
getting execution times
$ mysql -vv -e 
'select rating,count(*) from sakila.film
group by rating'
+--------+----------+
| rating | count(*) |
+--------+----------+
| G      |       178 |
| PG     |       194 |
| PG-13 |        223 |
| R      |       195 |
| NC-17 |        210 |
+--------+----------+
5 rows in set (0.00 sec)            131


Sunday, August 21, 11
getting execution times (batch mode)
$echo 'select rating,count(*) from sakila.film group
by rating' | mysql -vv
--------------
select rating,count(*) from sakila.film group by
rating
--------------

rating count(*)
G 178
PG 194
PG-13 223
R 195
NC-17 210
5 rows in set

                                             132


Sunday, August 21, 11
getting execution times (batch mode)
$ echo 'select rating,count(*) from sakila.film group
by rating' | mysql -vvv
--------------
select rating,count(*) from sakila.film group by
rating
--------------
+--------+----------+
| rating | count(*) |
+--------+----------+
| G      |      178 |
| PG     |      194 |
| PG-13 |       223 |
| R      |      195 |
| NC-17 |       210 |
+--------+----------+
                                             133
5 rows in set (0.00 sec)
Sunday, August 21, 11
advanced command line techniques



                        getting
       _$

                        distinct
                        results134


Sunday, August 21, 11
getting a single value
$ mysql -e "show variables like 'port'"
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306 |
+---------------+-------+

# Here, we only want the port number




                                       135


Sunday, August 21, 11
getting a single value
$ mysql -NB -e "show variables like 'port'"
 port           3306


# no header, batch mode
# still two values




                                    136


Sunday, August 21, 11
getting a single value
$ mysql -NB 
  -e "show variables like 'port'" 
  | awk '{print $2}'

3306

$ mysql -NB 
  -e "show variables like 'port'" 
 | perl -lane 'print $F[1]'

3306
# filtering the wanted value
                                      137


Sunday, August 21, 11
getting a single value: is replication
    working?
$ mysql 
  -e "show slave status G" 
 | grep -i slave_io_running

                        Slave_IO_Running: Yes


# too many things.
# We only want a 'yes' or 'no'

                                                138


Sunday, August 21, 11
getting a single value: is replication
    working?
$ mysql 
  -e "show slave status G" 
  | grep -i "slave_io_running" 
  | perl -lane 'print $F[1]'

Yes


# yes!

                                     139


Sunday, August 21, 11
What's perl -lane?




                         140


Sunday, August 21, 11
What's perl -lane?   perl -lane
                         must
                         turn perl




                             140


Sunday, August 21, 11
Perl command line must-know facts (1)
perl -e 'print "hellon"'
# executes perl code




                              141


Sunday, August 21, 11
Perl command line must-know facts (2)
perl -ne 'print if /^a/'
# starts a loop from standard input
# and executes the perl code for each
# iteration

perl -MO=Deparse -ne 'print if /^a/'
LINE: while (defined($_ = <ARGV>)) {
    print $_ if /^a/;
}

                               142


Sunday, August 21, 11
Perl command line must-know facts (3)
perl -pe 's/(^aw+)/$1/'
# like -ne, but prints each line

$ perl -MO=Deparse -pe 's/(^aw+)/$1/'
LINE: while (defined($_ = <ARGV>)) {
    s/(^aw+)/$1/;
}
continue {
    print $_;
}
                               143


Sunday, August 21, 11
Perl command line must-know facts (4)
perl -le 'print "hello"'
# strips newlines from input and adds
# them to output

$ perl -e 'print "hello"'
hello$

$ perl -le 'print "hello"'
hello
$
                               144


Sunday, August 21, 11
Perl command line must-know facts (5)
perl -lane 'print $F[0]'
# splits input into @F array

$ echo "a b c" | 
   perl -lane 'print $F[1]'
b

$ echo "a b c" | 
  perl -lane 'print $F[2]'
c
                               145


Sunday, August 21, 11
Perl command line must-know facts (6)
Perl and shell contention for $




 #!/bin/bash

                        Take the $$$ and run
                                           146


Sunday, August 21, 11
Beware of $VARIABLES on the
command line
$ perl -le "$x=1; print $x"
syntax error at -e line 1, near "="
Execution of -e aborted due to
compilation errors.




                               147


Sunday, August 21, 11
double quotes
Beware of $VARIABLES on theconsumed by the
                           allow the shell to
                           shell, before Perl
                           interpolate
command line               can see it
                           variables
$ perl -le "$x=1; print $x"
syntax error at -e line 1, near "="
Execution of -e aborted due to
compilation errors.




                                   147


Sunday, August 21, 11
double quotes
Beware of $VARIABLES on theconsumed by the
                           allow the shell to
                           shell, before Perl
                           interpolate
command line               can see it
                           variables
$ perl -le "$x=1; print $x"
syntax error at -e line 1, near "="
Execution of -e aborted due to
compilation errors.
                            consumed by the
                            shell, before Perl
                            can see it




                                   147


Sunday, August 21, 11
double quotes
Beware of $VARIABLES on the   consumed by the
                              allow the shell to
                              shell, before Perl
                              interpolate
command line                  can see it
                              variables
$ perl -le "$x=1; print $x"
syntax error at -e line 1, near "="
Execution of -e aborted due to
compilation errors.
                               consumed by the
                               shell, before Perl
$ perl -le '$x=1; print $x'    can see it
1


                                      147


Sunday, August 21, 11
double quotes
Beware of $VARIABLES on the   consumed by the
                              allow the shell to
                              shell, before Perl
                              interpolate
command line                  can see it
                              variables
$ perl -le "$x=1; print $x"
syntax error at -e line 1, near "="
Execution of -e aborted due to
compilation errors.
                               consumed by the
                               shell, before Perl
$ perl -le '$x=1; print $x'    can see it
1
                              single quotes the
                              consumed by
                              prevent variable
                              shell, before Perl
                              consumption by
                              can shell it
                              the see147
Sunday, August 21, 11
advanced command line techniques


        combining
         column
          names
                               148


Sunday, August 21, 11
combining column names
$ mysql -N -e 'desc world.City'
+-------------+----------+----+-----+
|          ID | int(11) | NO | PRI |
|        Name | char(35) | NO |     |
| CountryCode | char(3) | NO |      |
|    District | char(20) | NO |     |
| Population | int(11) | NO |       |
+-------------+----------+----+-----+



                                   149


Sunday, August 21, 11
combining column names
#     Expected result:
#     SELECT CONCAT_WS('|',
#     ID,Name,CountryCode,District,
#     Population) from City




                                      150


Sunday, August 21, 11
combining column names (I)
echo "select concat_ws('|',
  $(mysql -N -e 'desc world.City' | 
   perl -lane 'push @f, $F[0];' 
        -e 'END{print join ",", @f}'))
from world.City"
select concat_ws('|',
ID,Name,CountryCode,District,Populatio
n) from world.City


                                 151


Sunday, August 21, 11
combining column names (II)
echo "select concat_ws('|', $(
  mysql -NB -e 'select
group_concat(column_name) from
information_schema.columns where
table_name="City" and
table_schema="world"')) from
world.City"
select concat_ws('|',
ID,Name,CountryCode,District,Populatio
n) from world.City
                                  152


Sunday, August 21, 11
combining column names (IIa)
echo "select concat_ws('|', $(
  mysql -NB -e 'select
group_concat(column_name) from
information_schema.columns where
table_name="Country" and
table_schema="world"')) from
world.Country"
select concat_ws('|',
Code,Name,Continent,Region,SurfaceArea,Inde
pYear,Population,LifeExpectancy,GNP,GNPOld,
LocalName,GovernmentForm,HeadOfState,Capita
l,Code2) from world.Country         153


Sunday, August 21, 11
piping the result back to mysql
echo "select concat_ws('|', $(
  mysql -NB -e 'select
group_concat(column_name) from
information_schema.columns where
table_name="Country" and
table_schema="world"')) as line from
world.Country" | mysql | head -n 4
line
AFG|Afghanistan|Asia|Southern and Central Asia|652090.00|1919|
22720000|45.9|5976.00|Afganistan/Afqanestan|Islamic Emirate|
Mohammad Omar|1|AF
NLD|Netherlands|Europe|Western Europe|41526.00|1581|15864000|
78.3|371362.00|360478.00|Nederland|Constitutional Monarchy|
Beatrix|5|NL
ANT|Netherlands Antilles|North America|Caribbean|800.00|217000|
74.7|1941.00|Nederlandse Antillen|Nonmetropolitan Territory of
                                                      154
The Netherlands|Beatrix|33|AN
Sunday, August 21, 11
advanced command line techniques


                $_

                        dumping
                         data
                                155


Sunday, August 21, 11
advanced command line techniques


                $_

                        dumping
                         data
                                155


Sunday, August 21, 11
dumping a tab delimited data set
# the naive way
$ mysql 
  -e "SELECT *
  into outfile '/tmp/city_data'
from world.City"

# it works only if:
# - /tmp/city_data does not exist
# - /tmp is world writable

                                  156


Sunday, August 21, 11
dumping a tab delimited data set
$ mysql -B -N 
  -e "SELECT * from world.City" 
  > /tmp/city_data

# it works always

# if you omit the "-N" it also
# includes a header


                                  157


Sunday, August 21, 11
dumping a CSV
$ mysql -B 
  -e "SELECT * from world.City" 
 | perl -F"t" -lane 
  'print join ",",
   map {s/"/""/g;
      /^[d.]+$/ ? $_ : qq("$_")}
   @F ' 
  > /tmp/city_data


                               158


Sunday, August 21, 11
dumping a CSV
$ mysql -B 
  -e "SELECT * from world.City" 
 | perl -F"t" -lane 
  'print join ",",    splits the line by tabs, instead
   map {s/"/""/g;     of the default whitespace
      /^[d.]+$/ ? $_ : qq("$_")}
   @F ' 
  > /tmp/city_data


                                               158


Sunday, August 21, 11
advanced command line techniques




      script
        it
                               159


Sunday, August 21, 11
use the mysql.sh script
       §    The companion code for this tutorial
       §    http://tinyurl.com/cli-tut-code-2010
       §    It will save you much typing
       §    But use it at your own risk!




                                            160


Sunday, August 21, 11
Usage
      • download the script
      • load it

         $ source mysql.sh




                              161


Sunday, August 21, 11
mysql.sh functions
      •   my_batch "query"
      •   returns the result of the query.
      •   Without header
      •   Without box

   $      my_batch "SELECT * FROM test.t1"
   1      aaa
   2      bbb
   3      ccc
                                             162


Sunday, August 21, 11
mysql.sh functions
      • my_value "what"
      • returns a single value

      • e.g.
      $ my_value "version()"
      5.1.49

      $ my_value "@@server_id"
      1
                                 163


Sunday, August 21, 11
mysql.sh functions
      • my_var "what"
      • returns the value of a given variable

      • e.g.
      $ my_var port
      3306

      $ my_var datadir
      /usr/local/mysql/data
                                                164


Sunday, August 21, 11
mysql.sh functions
      • my_status "what"
      • returns the value of a given status item

      • e.g.
      $ my_status com_select
      2653

      $ my_status connections
      452
                                                   165


Sunday, August 21, 11
mysql.sh functions
      • my_dump_dataset "query" [header]
      • returns the values of a given query separated by tabs
      • if a header is requested, it will be part of the result
      • e.g.
      $ my_dump_dataset "select * from
      world.City" | head -n 5
      1 Kabul AFG Kabol 1780000
      2 Qandahar AFG Qandahar 237500
      3 Herat AFG Herat 186800
      4 Mazar-e-Sharif AFG Balkh 127800
                                                            166
      5 Amsterdam NLD Noord-Holland 731200
Sunday, August 21, 11
mysql.sh functions
      • my_csv "query" [separator]
      • returns the values of a given query separated by
        commas, or by a given separator
      • e.g.
$ my_csv 'select * from world.City' |
head -n 3
"ID","Name","CountryCode","District","
Population"
1,"Kabul","AFG","Kabol",1780000
2,"Qandahar","AFG","Qandahar",237500
                                                       167


Sunday, August 21, 11
inside the command line client

     handling


                                           :-)
                                       @         @


                                           $_



                        output
                                     168


Sunday, August 21, 11
pager
mysql> SELECT * FROM world.City;

rec …
rec …
rec …

4000 + records
unreadable


                               169


Sunday, August 21, 11
pager
mysql> pager less
PAGER set to 'less'
mysql> SELECT * FROM world.City;

# [ records in a manageable window ]

mysql> nopager
PAGER set to stdout

# back to normal
                               170


Sunday, August 21, 11
More pager tricks
mysql> pager vim -
# like 'less', but you can also edit
# the results and eventually save
# them




                               171


Sunday, August 21, 11
More pager tricks
mysql> pager md5sum
PAGER set to 'md5sum'
mysql> select * from City;
5d17ffa50d6da200dee621823ade2543          -
4079 rows in set (0.01 sec)

#      produce a CRC for the result set
#      instead of displaying it.
#      Useful for data comparison.
#      (Thanks to Baron Schwartz
                                    172


Sunday, August 21, 11
Comparing data sets with md5sum
mysql> select * from City;
5d17ffa50d6da200dee621823ade2543   -

mysql> select * from City order by ID;
5d17ffa50d6da200dee621823ade2543 -

mysql> select * from City order by name;
5ab980f5b69a6e65d3b8cd5a95ec94e0 -

mysql> select * from City order by
District;
2bf37cbe91b3ffeaebc8c4b6084b8784 -     173


Sunday, August 21, 11
Comparing data sets with md5sum
mysql> select * from City;
5d17ffa50d6da200dee621823ade2543   -

mysql> select * from City order by ID;
5d17ffa50d6da200dee621823ade2543 -

mysql> select * from City order by name;
5ab980f5b69a6e65d3b8cd5a95ec94e0 -

mysql> select * from City order by
District;
2bf37cbe91b3ffeaebc8c4b6084b8784 -     173


Sunday, August 21, 11
More pager tricks
mysql>                  pager cat > /tmp/t1.txt
mysql>                  select "one" union select
"two";
mysql>                  pager cat > /tmp/t2.txt
mysql>                  select "one" union select
"TWO";
mysql>                  nopager
mysql>                  ! vimdiff -o /tmp/t[12].txt

# see the difference between two
# datasets
                                                174


Sunday, August 21, 11
175


Sunday, August 21, 11
logging sessions
mysql> tee mylog.txt

#      logs everything that you see on
#      the screen.
#      your commands, the results,
#      warnings, error messages, and so on.

mysql> notee

# back to normal
                                    176


Sunday, August 21, 11
read more
   § http://datacharmer.blogspot.com




Sunday, August 21, 11
THANKS!
             ?
                                  Question
                                    time
                                Comments on Twitter:
                                @datacharmer
      This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License.
Sunday, August 21, 11
to do
   § add dead languages
      § comparing Latin and ancient Greek to COBOL and
         Pascal
   § add new tricks
      § {x,y} expansion in bash
      § G in MySQL
      §




Sunday, August 21, 11

More Related Content

More from Giuseppe Maxia

Dbdeployer, the universal installer
Dbdeployer, the universal installerDbdeployer, the universal installer
Dbdeployer, the universal installerGiuseppe Maxia
 
Test complex database systems in your laptop with dbdeployer
Test complex database systems in your laptop with dbdeployerTest complex database systems in your laptop with dbdeployer
Test complex database systems in your laptop with dbdeployerGiuseppe Maxia
 
A quick tour of Mysql 8 roles
A quick tour of Mysql 8 rolesA quick tour of Mysql 8 roles
A quick tour of Mysql 8 rolesGiuseppe Maxia
 
Synchronise your data between MySQL and MongoDB
Synchronise your data between MySQL and MongoDBSynchronise your data between MySQL and MongoDB
Synchronise your data between MySQL and MongoDBGiuseppe Maxia
 
Juggle your data with Tungsten Replicator
Juggle your data with Tungsten ReplicatorJuggle your data with Tungsten Replicator
Juggle your data with Tungsten ReplicatorGiuseppe Maxia
 
Tungsten Replicator tutorial
Tungsten Replicator tutorialTungsten Replicator tutorial
Tungsten Replicator tutorialGiuseppe Maxia
 
Preventing multi master conflicts with tungsten
Preventing multi master conflicts with tungstenPreventing multi master conflicts with tungsten
Preventing multi master conflicts with tungstenGiuseppe Maxia
 
MySQL high availability power and usability
MySQL high availability power and usabilityMySQL high availability power and usability
MySQL high availability power and usabilityGiuseppe Maxia
 
Solving MySQL replication problems with Tungsten
Solving MySQL replication problems with TungstenSolving MySQL replication problems with Tungsten
Solving MySQL replication problems with TungstenGiuseppe Maxia
 
State of the art of MySQL replication and clustering
State of the art of MySQL replication and clusteringState of the art of MySQL replication and clustering
State of the art of MySQL replication and clusteringGiuseppe Maxia
 
Testing mysql creatively in a sandbox
Testing mysql creatively in a sandboxTesting mysql creatively in a sandbox
Testing mysql creatively in a sandboxGiuseppe Maxia
 
Mysql 5.5 and 5.6 replication
Mysql 5.5 and 5.6 replicationMysql 5.5 and 5.6 replication
Mysql 5.5 and 5.6 replicationGiuseppe Maxia
 
Lightning talks percona live mysql_2012
Lightning talks percona live mysql_2012Lightning talks percona live mysql_2012
Lightning talks percona live mysql_2012Giuseppe Maxia
 

More from Giuseppe Maxia (20)

Dbdeployer, the universal installer
Dbdeployer, the universal installerDbdeployer, the universal installer
Dbdeployer, the universal installer
 
Test complex database systems in your laptop with dbdeployer
Test complex database systems in your laptop with dbdeployerTest complex database systems in your laptop with dbdeployer
Test complex database systems in your laptop with dbdeployer
 
Dbdeployer
DbdeployerDbdeployer
Dbdeployer
 
Dbdeployer
DbdeployerDbdeployer
Dbdeployer
 
A quick tour of Mysql 8 roles
A quick tour of Mysql 8 rolesA quick tour of Mysql 8 roles
A quick tour of Mysql 8 roles
 
MySQL document_store
MySQL document_storeMySQL document_store
MySQL document_store
 
Replication skeptic
Replication skepticReplication skeptic
Replication skeptic
 
Synchronise your data between MySQL and MongoDB
Synchronise your data between MySQL and MongoDBSynchronise your data between MySQL and MongoDB
Synchronise your data between MySQL and MongoDB
 
Juggle your data with Tungsten Replicator
Juggle your data with Tungsten ReplicatorJuggle your data with Tungsten Replicator
Juggle your data with Tungsten Replicator
 
MySQL in your laptop
MySQL in your laptopMySQL in your laptop
MySQL in your laptop
 
Script it
Script itScript it
Script it
 
Tungsten Replicator tutorial
Tungsten Replicator tutorialTungsten Replicator tutorial
Tungsten Replicator tutorial
 
Preventing multi master conflicts with tungsten
Preventing multi master conflicts with tungstenPreventing multi master conflicts with tungsten
Preventing multi master conflicts with tungsten
 
MySQL high availability power and usability
MySQL high availability power and usabilityMySQL high availability power and usability
MySQL high availability power and usability
 
Solving MySQL replication problems with Tungsten
Solving MySQL replication problems with TungstenSolving MySQL replication problems with Tungsten
Solving MySQL replication problems with Tungsten
 
State of the art of MySQL replication and clustering
State of the art of MySQL replication and clusteringState of the art of MySQL replication and clustering
State of the art of MySQL replication and clustering
 
Testing mysql creatively in a sandbox
Testing mysql creatively in a sandboxTesting mysql creatively in a sandbox
Testing mysql creatively in a sandbox
 
Mysql 5.5 and 5.6 replication
Mysql 5.5 and 5.6 replicationMysql 5.5 and 5.6 replication
Mysql 5.5 and 5.6 replication
 
Lightning talks percona live mysql_2012
Lightning talks percona live mysql_2012Lightning talks percona live mysql_2012
Lightning talks percona live mysql_2012
 
Replication 101
Replication 101Replication 101
Replication 101
 

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

Don't be a GUI rookie forever - Be in command! (line)

  • 1. Don’t be a rookie forever. Be in command! (line) Giuseppe Maxia @datacharmer $ This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License. Sunday, August 21, 11
  • 2. about me -Giuseppe Maxia § a.k.a. The Data Charmer § QA Director, Continuent, Inc § Long time hacking with database features § Formerly, database consultant, designer, coder. § A passion for QA § An even greater passion for open source § ... and community § Passionate blogger § http://datacharmer.blogspot.com Sunday, August 21, 11
  • 3. What this tutorial is about § Providing tools and tips for command line users; § Learn a few tricks to make you achieve more and type less. Sunday, August 21, 11
  • 4. What this tutorial is about § Providing tools and tips for command line users; § Learn a few tricks to make you achieve more and type less. § Making GUI enthusiasts green with envy; bar foo baz Sunday, August 21, 11
  • 5. This tutorial § A quick guide at the command line usage § A practical case for database admins § but ... § Useful for all Sunday, August 21, 11
  • 6. Problem § One document contains one date in 'mm/dd/yyyy' format § Need to convert the date into the 'yyyy-mm-dd' format (or dd.mm.yyyy) GUI USER SOLUTION § open the document with a word processor § change the date § Command line USER SOLUTION § Probably the same Sunday, August 21, 11
  • 7. Problem § One document contains many dates in 'mm/dd/yyyy' format § Need to convert the dates into the 'yyyy-mm-dd' format (or dd.mm.yyyy) GUI USER SOLUTION § open the document with an advanced word processor § hope it supports regular expressions § Command line USER SOLUTION § Use vi or emacs. Do a search-and-replace operation § Or use the next page solution Sunday, August 21, 11
  • 8. Problem § Many documents contain many dates in 'mm/dd/yyyy' format § Need to convert the dates in all documents into the 'yyyy-mm-dd' format (or dd.mm.yyyy) GUI USER SOLUTION § Realizes that it will take days to do this manually § Scream § Command Line USER SOLUTION § uses sed or perl to do the replacement in one line Sunday, August 21, 11
  • 9. the command line ? WHY 8 Sunday, August 21, 11
  • 10. An educational story 1985-90 1991 1993 1994 1995-97 1998-99 2000-2001 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 11. An educational story 1985-90 • MS-DOS 1991 1993 1994 1995-97 1998-99 2000-2001 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 12. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 1994 1995-97 1998-99 2000-2001 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 13. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 1995-97 1998-99 2000-2001 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 14. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 • Windows NT 1995-97 1998-99 2000-2001 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 15. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 • Windows NT 1995-97 • Windows 95 1998-99 2000-2001 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 16. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 • Windows NT 1995-97 • Windows 95 1998-99 • Windows 98 2000-2001 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 17. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 • Windows NT 1995-97 • Windows 95 1998-99 • Windows 98 2000-2001 • Windows 2000 2001-2006 2007-2009 2010- 9 Sunday, August 21, 11
  • 18. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 • Windows NT 1995-97 • Windows 95 1998-99 • Windows 98 2000-2001 • Windows 2000 2001-2006 • Windows XP 2007-2009 2010- 9 Sunday, August 21, 11
  • 19. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 • Windows NT 1995-97 • Windows 95 1998-99 • Windows 98 2000-2001 • Windows 2000 2001-2006 • Windows XP 2007-2009 • Windows Vista 2010- 9 Sunday, August 21, 11
  • 20. An educational story 1985-90 • MS-DOS 1991 • Windows 3.0 1993 • Windows 3.1 1994 • Windows NT 1995-97 • Windows 95 1998-99 • Windows 98 2000-2001 • Windows 2000 2001-2006 • Windows XP 2007-2009 • Windows Vista 2010- • Windows 7 9 Sunday, August 21, 11
  • 21. An educational story 1985-90 • MS-DOS • Unix shell 1991 • Windows 3.0 1993 • Windows 3.1 • Linux 1994 • Windows NT 1995-97 • Windows 95 1998-99 • Windows 98 2000-2001 • Windows 2000 2001-2006 • Windows XP • Mac OSX 2007-2009 • Windows Vista 2010- • Windows 7 9 Sunday, August 21, 11
  • 22. Why the command line • portability • efficiency • fun 10 Sunday, August 21, 11
  • 23. the command line (for rookies) |||| NO PANIC 11 Sunday, August 21, 11
  • 24. Command line panic (for rookies) $_ Sunday, August 21, 11
  • 25. Command line panic (for rookies) $_ NOW WHAT? Sunday, August 21, 11
  • 26. the command line (for rookies) BASICS 13 Sunday, August 21, 11
  • 27. The shell • It's a command interpreter • There are many flavors > bash > zsh > ksh 14 Sunday, August 21, 11
  • 28. MySQL command line client • called "mysql" > Takes SQL commands > sends them to the server > gets results • but it can do much more ... 15 Sunday, August 21, 11
  • 29. other tools • Shell scripts • Aliases • Perl • awk • sort • …. and a lot of Unix little helper 16 Sunday, August 21, 11
  • 30. other tools • Shell scripts • Aliases • Perl which could replace everything else, of course • awk • sort • …. and a lot of Unix little helper 16 Sunday, August 21, 11
  • 31. in case it wasn't clear (yeah, for rookies) 17 Sunday, August 21, 11
  • 32. in case it wasn't clear (yeah, for rookies) • command line actions are 17 Sunday, August 21, 11
  • 33. in case it wasn't clear (yeah, for rookies) • command line actions are > commands (the name of the application to invoke) 17 Sunday, August 21, 11
  • 34. in case it wasn't clear (yeah, for rookies) • command line actions are > commands (the name of the application to invoke) > parameters (optional arguments for the application) 17 Sunday, August 21, 11
  • 35. in case it wasn't clear (yeah, for rookies) • command line actions are > commands (the name of the application to invoke) > parameters (optional arguments for the application) > and the ENTER key 17 Sunday, August 21, 11
  • 36. in case it wasn't clear (yeah, for rookies) • command line actions are > commands (the name of the application to invoke) > parameters (optional arguments for the application) > and the ENTER key Enter 17 Sunday, August 21, 11
  • 37. The Unix philosophy (1) • One tool for every feature > make one tool that does one thing well > for many features, make many tools > make them work together (see next slide) 18 Sunday, August 21, 11
  • 38. The Unix philosophy (2) • To make several tool cooperate: > pipe the output of one tool to the input of another one. > for more actions, pipe more tools $ sort < filename | uniq | nl 19 Sunday, August 21, 11
  • 39. Unix pipes 20 Sunday, August 21, 11
  • 40. Unix pipes application < input 20 Sunday, August 21, 11
  • 41. Unix pipes application < input application > output 20 Sunday, August 21, 11
  • 42. Unix pipes application < input application > output application < input > output 20 Sunday, August 21, 11
  • 43. Unix pipes application < input application > output application < input > output application | application 20 Sunday, August 21, 11
  • 44. Unix pipes application < input application > output application < input > output application | application output input 20 Sunday, August 21, 11
  • 45. Unix pipes = parallel processing 21 Sunday, August 21, 11
  • 46. Unix pipes = parallel processing application | application 21 Sunday, August 21, 11
  • 47. Unix pipes = parallel processing application | application 21 Sunday, August 21, 11
  • 48. Unix pipes = parallel processing application | application output 21 Sunday, August 21, 11
  • 49. Unix pipes = parallel processing application | application output input 21 Sunday, August 21, 11
  • 50. Unix pipes = parallel processing application | application output input 21 Sunday, August 21, 11
  • 51. Unix pipes = parallel processing application | application output input 21 Sunday, August 21, 11
  • 52. Unix pipes = parallel processing application | application output input 21 Sunday, August 21, 11
  • 53. Who gets what • shell • application • database server • pager 22 Sunday, August 21, 11
  • 54. who gets what shell prompt $ mysql mysql client mysql server 23 Sunday, August 21, 11
  • 55. who gets what any host mysql server shell mysql client 24 Sunday, August 21, 11
  • 56. who gets what $ mysql -u username -ppassword First the application then the server 25 Sunday, August 21, 11
  • 57. who gets what $ mysql -u username -ppassword -e "select VERSION()" goes to the client, then the server goes to the server 26 Sunday, August 21, 11
  • 58. who gets what mysql> help mysql> pager less goes to the client only mysql> select 1; goes to the server 27 Sunday, August 21, 11
  • 59. the command line readline 28 Sunday, August 21, 11
  • 60. readline • Common component > shell > mysql client > many CLI applications 29 Sunday, August 21, 11
  • 61. Main cursor movements Ctrl A Start/End of line Ctrl E Meta B Back/Forward one word Meta F previous/next command Ctrl L clear screen and take current line on top Ctrl R Search history 30 Sunday, August 21, 11
  • 62. Changing text Meta U Uppercase word Meta L Lowercase word Ctrl D delete word Ctrl K delete to end of line Ctrl - undo for more tips: $ man readline 31 Sunday, August 21, 11
  • 63. Some conventions in this talk $ command at the shell mysql> command at the mysql prompt 32 Sunday, August 21, 11
  • 64. The command line friends #! handy Sunday, August 21, 11 tools 33
  • 65. your best friends at the command line • man • ls • cd • find • grep • date • echo • pwd • mv 34 • cp Sunday, August 21, 11
  • 66. man {command_name} • Tells you how to use a command man ls 35 Sunday, August 21, 11
  • 67. ls [directory] • lists contents of current [or given] directory ls ls /some/path ls *.txt 36 Sunday, August 21, 11
  • 68. cd [directory] • change directory to given path • takes to $HOME directory if no path is given cd /some/path cd .. 37 Sunday, August 21, 11
  • 69. find {directory} [conditions] • finds files in the given directory that satisfy conditions find $HOME/docs -name "*mouse*" 38 Sunday, August 21, 11
  • 70. grep {pattern} filename • finds pattern matching rows in filename grep Munich *.txt grep "Munich|Berlin" *.txt grep "[0-9][0-9]:[0-9][0-9]" a.txt 39 Sunday, August 21, 11
  • 71. date [layout] • displays the current date and time, with optional layout date Tue Aug 16 08:33:04 CEST 2011 date '+%Y-%m-%d' 2011-08-16 40 Sunday, August 21, 11
  • 72. echo "message" • displays the given message and/or variables echo "hi" hi GREETINGS='Hello, there!' echo $GREETINGS Hello, there! 41 Sunday, August 21, 11
  • 73. pwd • displays the current path (Print Working Directory pwd /home/gmax/test_dir 42 Sunday, August 21, 11
  • 74. mv old_file_name new_file_name • moves a file from one place to another • renames a file mv ugly.txt /some/other/path mv *.txt /storage/texts mv ugly.txt beautiful.txt 43 Sunday, August 21, 11
  • 75. cp file_name destination • copies a file from one place to another • creates a copy of a file cp ugly.txt /some/other/path cp *.txt /storage/texts cp ugly.txt beautiful.txt 44 Sunday, August 21, 11
  • 76. other important friends at the command line • rm • mkdir • rmdir • cat • sed • strings • wc • head • tail • more/less 45 • sort Sunday, August 21, 11
  • 77. rm file_name • removes a file rm ugly.txt rm *.txt ### DANGER!!!! rm -r * rm -rf * 46 Sunday, August 21, 11
  • 78. mkdir/rmdir directory • creates or removes a directory mkdir mydir rmdir mydir 47 Sunday, August 21, 11
  • 79. cat • shows the contents of a file cat addresses.txt 48 Sunday, August 21, 11
  • 80. sed [option] file • performs editing on a file sed -e 's/Ship/Airplane/' travel.txt 49 Sunday, August 21, 11
  • 81. strings filename • extracts printable text from a file strings /bin/ls 50 Sunday, August 21, 11
  • 82. wc filename • counts words (and characters and lines) in a file wc .bashrc 72 164 2842 .bashrc # (lines, words, characters) 51 Sunday, August 21, 11
  • 83. head/tail filename • display the first or the last lines of a file head long_file.txt head -n 5 long_file.txt tail long_file.txt tail -n 1 long_file.txt 52 Sunday, August 21, 11
  • 84. more/less filename • display a file with scrollable pages # old: inefficient more filename.txt # new: preferred less filename.txt 53 Sunday, August 21, 11
  • 85. sort filename • displays the ordered contents of a filename sort unordered.txt sort unordered.txt > sorted.txt 54 Sunday, August 21, 11
  • 86. #! mixing languages 55 Sunday, August 21, 11
  • 87. This is a story about languages Sunday, August 21, 11
  • 88. you got to understand, Bernie, it's not personal. It's just that you are obsolete We use language to talk to computers Sunday, August 21, 11
  • 89. 10 print "hello" We use 20 goto 10 languages to talk to computers Sunday, August 21, 11
  • 90. I am a polyglot Sunday, August 21, 11
  • 91. An imperfect polyglot, actually Sunday, August 21, 11
  • 92. I speak Italian Sunday, August 21, 11
  • 93. I speak Italian with a clear Sardinian accent Sunday, August 21, 11
  • 94. I speak English Sunday, August 21, 11
  • 95. I speak English with a distinct Italian accent Sunday, August 21, 11
  • 96. I speak Perl Sunday, August 21, 11
  • 97. I speak Perl with a hint of a C accent Sunday, August 21, 11
  • 98. I speak French and Spanish Sunday, August 21, 11
  • 99. I speak French and Spanish but since I use them very little, they have melted with Italian and English Sunday, August 21, 11
  • 100. I speak #!/bin/bash Bash Sunday, August 21, 11
  • 101. I speak #!/bin/bash Bash with a strong Perl accent Sunday, August 21, 11
  • 102. I speak fluent Italian La donzelletta vien dalla campagna, in sul calar del sole, col suo fascio dell'erba e reca in mano un mazzolino di rose e viole, onde, siccome suole, ornare ella si appresta ... Sunday, August 21, 11
  • 103. However, Sardinian comes handy sometimes Maissavida ti frimisti! (*) (*) May you never stop Sunday, August 21, 11
  • 104. I speak fluent English When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation. Sunday, August 21, 11
  • 105. I speak fluent English When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation. hmm. wrong flag Sunday, August 21, 11
  • 106. I speak fluent English When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation. Sunday, August 21, 11
  • 107. But sometimes Italian is still necessary barista al fresco pasta maestro espresso tempo vendetta soprano finale piano dilettante cappuccino stucco stiletto virtuoso fiasco presto lotto pizza bravo lasagna studio spaghetti stanza Sunday, August 21, 11
  • 108. And sometimes Italian is needed I tuoi perversi defunti!(*) (*) Your wicked ancestors! Sunday, August 21, 11
  • 109. Although Sardinian is still effective here Ancu ti currullidi sa giustizia (*) (*) May the rule of law chase you Sunday, August 21, 11
  • 110. I speak Perl fluently #!/usr/bin/perl use strict; use warnings; use File::Find; while (my $line = <stdin>){ # … Sunday, August 21, 11
  • 111. Sometimes, I need help from C use Inline C; print "9 + 16 = ", add(9, 16), "n"; __END__ __C__ int add(int x, int y) { return x + y; } Sunday, August 21, 11
  • 112. Most of my work at the command line is Bash $ for D in $HOME/*/; do du -sh $D; > done > /tmp/occupancy #!/bin/bash Sunday, August 21, 11
  • 113. And sometimes, a pinch of Perl can help $ perl -pe 's{(dd)-(dd)-(dddd)}{$3-$1-$2}g' < rawfile.txt > betterfile.txt #!/bin/bash Sunday, August 21, 11
  • 114. And then on top of all this, I need to speak SQL $ mysql -e 'SELECT COUNT(*) FROM dbname.tbl_name WHERE col_name = 1 and other_col="A" ' Sunday, August 21, 11
  • 115. I wish I could say that my SQL has a Perlish accent $ mysql -e 'SELECT COUNT(*) FROM dbname.tbl_name WHERE col_name = 1 and other_col="A" ' use strict; use DBI;? Sunday, August 21, 11
  • 116. I wish I could say that my SQL has a Perlish accent $ mysql -e 'SELECT COUNT(*) FROM dbname.tbl_name WHERE col_name = 1 and other_col="A" ' but it wouldn't be true Sunday, August 21, 11
  • 117. I could curse in Perl $ perl -pe 's{(dd)-(dd)-(ddd d)}{$3-$1-$2}g' < rawfile.txt > betterfile.txt (*) But it would not get me far. (*) already translated Sunday, August 21, 11
  • 119. Then I will need to mix languages. Sunday, August 21, 11
  • 120. Then I will need to mix languages. This talk will show exactly that. Sunday, August 21, 11
  • 121. Then I will need to mix languages. This talk will show exactly that. Mixing languages. Sunday, August 21, 11
  • 122. Then I will need to mix languages. This talk will show exactly that. Mixing languages. Yes. Sunday, August 21, 11
  • 123. Then I will need to mix languages. This talk will show exactly that. Mixing languages. Yes. $ at the command line Sunday, August 21, 11
  • 124. the Bash shell #! bash 81 Sunday, August 21, 11
  • 125. components • commands • aliases • variables • functions 82 Sunday, August 21, 11
  • 126. commands $ echo "something" something 83 Sunday, August 21, 11
  • 127. aliases $ alias mydate='mysql -e "select NOW()"' $ mydate +---------------------+ | now() | +---------------------+ | 2010-04-12 07:14:19 | +---------------------+ 84 Sunday, August 21, 11
  • 128. aliases $ alias myself='mysql' $ myself -e "select NOW()"' +---------------------+ | now() | +---------------------+ | 2010-04-12 07:14:19 | +---------------------+ 85 Sunday, August 21, 11
  • 129. variables $ MYBATCH='mysql -N -B' $ MYQUERY='select curdate()' $ $MYBATCH -e "$MYQUERY" 2010-04-12 86 Sunday, August 21, 11
  • 130. nesting variables # t.sh CMD="SELECT TABLE_NAME" TBL='information_schema.tables' WHC1="TABLE_SCHEMA='mysql'" WHC2="TABLE_NAME like 'u%' " Q1="$CMD FROM $TBL" Q2="WHERE $WHC1 AND $WHC2" Q="$Q1 $Q2" echo $Q echo $Q | mysql 87 Sunday, August 21, 11
  • 131. nesting variables $ sh t.sh SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA='mysql' AND TABLE_NAME like 'u%' TABLE_NAME user 88 Sunday, August 21, 11
  • 132. the mysql command line client mysql> 89 Sunday, August 21, 11
  • 133. SQL commands from a file $ mysql < filename.sql mysql> source filename.sql • executes the commands contained in filename.sql • commands can be queries understood by the server • and commands for the client 90 Sunday, August 21, 11
  • 134. SQL commands at the command line $ application | mysql $ echo "SELECT 1" | mysql $ mysql -e "SELECT 1" • executes the commands from standard input • commands can be queries understood by the server • and commands for the client 91 Sunday, August 21, 11
  • 135. batch mode $ echo "select curdate()" | mysql curdate() 2010-04-12 92 Sunday, August 21, 11
  • 136. table mode $ echo "select curdate()" | mysql -t +------------+ | curdate() | +------------+ | 2010-04-12 | +------------+ 93 Sunday, August 21, 11
  • 137. table mode $ mysql -e "select curdate()" +------------+ | curdate() | +------------+ | 2010-04-12 | +------------+ 94 Sunday, August 21, 11
  • 138. Forcing batch mode mysql -B -e 'select curdate()' curdate() 2010-04-12 95 Sunday, August 21, 11
  • 139. Forcing batch mode - no header mysql -N -B -e 'select curdate()' 2010-04-12 ANT! PO RT IM 96 Sunday, August 21, 11
  • 140. Shell + mysql $ echo "The current server's date is `mysql -N -B -e 'select curdate()'`." $ echo "The current server's date is $(mysql -N -B -e 'select curdate()')." 97 Sunday, August 21, 11
  • 141. advanced command line techniques (((((( (: @ @ - $_ loops 98 Sunday, August 21, 11
  • 142. loops basics $ for N in 1 2 3 > do > echo $N > done 1 2 3 99 Sunday, August 21, 11
  • 143. loops basics $ for N in 1 2 3 ; do echo $N ; done 1 2 3 100 Sunday, August 21, 11
  • 144. loops basics $ for N in $(seq 1 3) ; do echo "this is number $N" ; done this is number 1 this is number 2 this is number 3 101 Sunday, August 21, 11
  • 145. loops from file $ head /usr/share/dict/words A a aa aal aalii aam Aani aardvark aardwolf 102 Sunday, August 21, 11
  • 146. loops from file $ for U in $(head /usr/share/dict/words ) ; do perl -le 'print uc shift' $U ; done A A AA AAL AALII AAM AANI 103 Sunday, August 21, 11
  • 147. loops from mysql results $ mysql -B -N -e 'show tables from world' City Country CountryLanguage 104 Sunday, August 21, 11
  • 148. loops from mysql results $ for T in $(mysql -B -N -e 'show tables from world') ; > do echo "CREATE TABLE world2.$T LIKE world.$T;" ; done CREATE TABLE world2.City LIKE world.City; CREATE TABLE world2.Country LIKE world.Country; CREATE TABLE world2.CountryLanguage LIKE world.CountryLanguage; 105 Sunday, August 21, 11
  • 149. piping loops back into mysql $ for T in $(mysql -B -N -e 'show tables from world') ; > do echo "CREATE TABLE world2.$T LIKE world.$T;" ; done > | mysql -vv 106 Sunday, August 21, 11
  • 150. advanced command line techniques nested :) @ @ - $_ #! #! #! #! loops #! #! 107 Sunday, August 21, 11
  • 151. doing something for every table in every database $ mysql -e "show databases" +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | sakila | | world | +--------------------+ 108 Sunday, August 21, 11
  • 152. doing something for every table in every database $ mysql -e "show tables from world" +-----------------+ | Tables_in_world | +-----------------+ | City | | Country | | CountryLanguage | +-----------------+ 109 Sunday, August 21, 11
  • 153. pseudocode for each database do for each table do print the table name 110 Sunday, August 21, 11
  • 154. actual code alias mybatch='mysql -B -N' for D in $(mybatch -e "SHOW SCHEMAS") do for T in $(mybatch -e "SHOW TABLES FROM $D") do echo "$D.$T" done done 111 Sunday, August 21, 11
  • 155. advanced command line techniques $HOME options files 112 Sunday, August 21, 11
  • 156. Default option files /etc/my.cnf /etc/mysql/my.cnf (Debian, Ubuntu) $BASEDIR/my.cnf $HOME/.my.cnf 113 Sunday, August 21, 11
  • 157. Custom option files $ mysql --no-defaults $ mysql --defaults-file=filename $ mysql --defaults-extra-file=filename 114 Sunday, August 21, 11
  • 158. Option files sections [mysqld] # option for server [client] # option for any mysql client [mysql] # options specific to 'mysql' CLI app 115 Sunday, August 21, 11
  • 160. Option files: caution # protect your option files! $ chmod 600 $HOME/.my.cnf $ ls -l .my.cnf -rw------- 1 [...] 10:04 .my.cnf 117 Sunday, August 21, 11
  • 161. prompt mysql> prompt gm (h) {u} [d] > PROMPT set to 'gm (h) {u} [d] > ' gm (localhost) {root} [(none)] > use test Database changed gm (localhost) {root} [test] > # h -> host # u -> user # d -> database 118 Sunday, August 21, 11
  • 162. advanced command line techniques (((((( (: @ @ - #! aliases 119 Sunday, August 21, 11
  • 163. An useful alias $ alias mysql_as_root= 'mysql -- defaults_file=~/.my_as_root.cnf' mysql_as_root -e "select user()" +----------------+ | user() | +----------------+ | root@localhost | +----------------+ 120 Sunday, August 21, 11
  • 165. Another useful alias alias mybatch='mysql -B -N ' mybatch -e "select version()" 5.1.45-log 122 Sunday, August 21, 11
  • 166. ( ) advanced command line techniques (((((( (: @ @ - #! functions 123 Sunday, August 21, 11
  • 167. functions • like aliases, but with parameters 124 Sunday, August 21, 11
  • 168. sample function function grant_new { mysql_as_root -e "GRANT $1 on $2 to $3 identified by "$4" " } $ grant_new SELECT "world.*" john john_secret 125 Sunday, August 21, 11
  • 169. sample function $ mysql_as_root -e 'show grants for johnG' *** 1. row *** Grants for john@%: GRANT USAGE ON *.* TO 'john'@'%' IDENTIFIED BY PASSWORD '*73A88CE13374128844E3ABB500F439A9C02C 53A3' *** 2. row *** Grants for john@%: GRANT SELECT ON `world`.* TO 'john'@'%' 126 Sunday, August 21, 11
  • 170. advanced command line techniques $_ getting query details127 Sunday, August 21, 11
  • 171. which query is being executed? # wrong.sql # this script has one error use test ; drop table if exists t1 ; create table t1 (id int); insert into t1 values (a); 128 Sunday, August 21, 11
  • 172. which query is being executed? $ mysql < wrong.sql ERROR 1054 (42S22) at line 4: Unknown column 'a' in 'field list' # WHERE IS THE ERROR? 129 Sunday, August 21, 11
  • 173. which query is being executed? $ mysql -v < wrong.sql -------------- drop table if exists t1 -------------- -------------- create table t1 (id int) -------------- -------------- insert into t1 values (a) -------------- ERROR 1054 (42S22) at line 4: Unknown column 'a' in 'field list' 130 Sunday, August 21, 11
  • 174. getting execution times $ mysql -vv -e 'select rating,count(*) from sakila.film group by rating' +--------+----------+ | rating | count(*) | +--------+----------+ | G | 178 | | PG | 194 | | PG-13 | 223 | | R | 195 | | NC-17 | 210 | +--------+----------+ 5 rows in set (0.00 sec) 131 Sunday, August 21, 11
  • 175. getting execution times (batch mode) $echo 'select rating,count(*) from sakila.film group by rating' | mysql -vv -------------- select rating,count(*) from sakila.film group by rating -------------- rating count(*) G 178 PG 194 PG-13 223 R 195 NC-17 210 5 rows in set 132 Sunday, August 21, 11
  • 176. getting execution times (batch mode) $ echo 'select rating,count(*) from sakila.film group by rating' | mysql -vvv -------------- select rating,count(*) from sakila.film group by rating -------------- +--------+----------+ | rating | count(*) | +--------+----------+ | G | 178 | | PG | 194 | | PG-13 | 223 | | R | 195 | | NC-17 | 210 | +--------+----------+ 133 5 rows in set (0.00 sec) Sunday, August 21, 11
  • 177. advanced command line techniques getting _$ distinct results134 Sunday, August 21, 11
  • 178. getting a single value $ mysql -e "show variables like 'port'" +---------------+-------+ | Variable_name | Value | +---------------+-------+ | port | 3306 | +---------------+-------+ # Here, we only want the port number 135 Sunday, August 21, 11
  • 179. getting a single value $ mysql -NB -e "show variables like 'port'" port 3306 # no header, batch mode # still two values 136 Sunday, August 21, 11
  • 180. getting a single value $ mysql -NB -e "show variables like 'port'" | awk '{print $2}' 3306 $ mysql -NB -e "show variables like 'port'" | perl -lane 'print $F[1]' 3306 # filtering the wanted value 137 Sunday, August 21, 11
  • 181. getting a single value: is replication working? $ mysql -e "show slave status G" | grep -i slave_io_running Slave_IO_Running: Yes # too many things. # We only want a 'yes' or 'no' 138 Sunday, August 21, 11
  • 182. getting a single value: is replication working? $ mysql -e "show slave status G" | grep -i "slave_io_running" | perl -lane 'print $F[1]' Yes # yes! 139 Sunday, August 21, 11
  • 183. What's perl -lane? 140 Sunday, August 21, 11
  • 184. What's perl -lane? perl -lane must turn perl 140 Sunday, August 21, 11
  • 185. Perl command line must-know facts (1) perl -e 'print "hellon"' # executes perl code 141 Sunday, August 21, 11
  • 186. Perl command line must-know facts (2) perl -ne 'print if /^a/' # starts a loop from standard input # and executes the perl code for each # iteration perl -MO=Deparse -ne 'print if /^a/' LINE: while (defined($_ = <ARGV>)) { print $_ if /^a/; } 142 Sunday, August 21, 11
  • 187. Perl command line must-know facts (3) perl -pe 's/(^aw+)/$1/' # like -ne, but prints each line $ perl -MO=Deparse -pe 's/(^aw+)/$1/' LINE: while (defined($_ = <ARGV>)) { s/(^aw+)/$1/; } continue { print $_; } 143 Sunday, August 21, 11
  • 188. Perl command line must-know facts (4) perl -le 'print "hello"' # strips newlines from input and adds # them to output $ perl -e 'print "hello"' hello$ $ perl -le 'print "hello"' hello $ 144 Sunday, August 21, 11
  • 189. Perl command line must-know facts (5) perl -lane 'print $F[0]' # splits input into @F array $ echo "a b c" | perl -lane 'print $F[1]' b $ echo "a b c" | perl -lane 'print $F[2]' c 145 Sunday, August 21, 11
  • 190. Perl command line must-know facts (6) Perl and shell contention for $ #!/bin/bash Take the $$$ and run 146 Sunday, August 21, 11
  • 191. Beware of $VARIABLES on the command line $ perl -le "$x=1; print $x" syntax error at -e line 1, near "=" Execution of -e aborted due to compilation errors. 147 Sunday, August 21, 11
  • 192. double quotes Beware of $VARIABLES on theconsumed by the allow the shell to shell, before Perl interpolate command line can see it variables $ perl -le "$x=1; print $x" syntax error at -e line 1, near "=" Execution of -e aborted due to compilation errors. 147 Sunday, August 21, 11
  • 193. double quotes Beware of $VARIABLES on theconsumed by the allow the shell to shell, before Perl interpolate command line can see it variables $ perl -le "$x=1; print $x" syntax error at -e line 1, near "=" Execution of -e aborted due to compilation errors. consumed by the shell, before Perl can see it 147 Sunday, August 21, 11
  • 194. double quotes Beware of $VARIABLES on the consumed by the allow the shell to shell, before Perl interpolate command line can see it variables $ perl -le "$x=1; print $x" syntax error at -e line 1, near "=" Execution of -e aborted due to compilation errors. consumed by the shell, before Perl $ perl -le '$x=1; print $x' can see it 1 147 Sunday, August 21, 11
  • 195. double quotes Beware of $VARIABLES on the consumed by the allow the shell to shell, before Perl interpolate command line can see it variables $ perl -le "$x=1; print $x" syntax error at -e line 1, near "=" Execution of -e aborted due to compilation errors. consumed by the shell, before Perl $ perl -le '$x=1; print $x' can see it 1 single quotes the consumed by prevent variable shell, before Perl consumption by can shell it the see147 Sunday, August 21, 11
  • 196. advanced command line techniques combining column names 148 Sunday, August 21, 11
  • 197. combining column names $ mysql -N -e 'desc world.City' +-------------+----------+----+-----+ | ID | int(11) | NO | PRI | | Name | char(35) | NO | | | CountryCode | char(3) | NO | | | District | char(20) | NO | | | Population | int(11) | NO | | +-------------+----------+----+-----+ 149 Sunday, August 21, 11
  • 198. combining column names # Expected result: # SELECT CONCAT_WS('|', # ID,Name,CountryCode,District, # Population) from City 150 Sunday, August 21, 11
  • 199. combining column names (I) echo "select concat_ws('|', $(mysql -N -e 'desc world.City' | perl -lane 'push @f, $F[0];' -e 'END{print join ",", @f}')) from world.City" select concat_ws('|', ID,Name,CountryCode,District,Populatio n) from world.City 151 Sunday, August 21, 11
  • 200. combining column names (II) echo "select concat_ws('|', $( mysql -NB -e 'select group_concat(column_name) from information_schema.columns where table_name="City" and table_schema="world"')) from world.City" select concat_ws('|', ID,Name,CountryCode,District,Populatio n) from world.City 152 Sunday, August 21, 11
  • 201. combining column names (IIa) echo "select concat_ws('|', $( mysql -NB -e 'select group_concat(column_name) from information_schema.columns where table_name="Country" and table_schema="world"')) from world.Country" select concat_ws('|', Code,Name,Continent,Region,SurfaceArea,Inde pYear,Population,LifeExpectancy,GNP,GNPOld, LocalName,GovernmentForm,HeadOfState,Capita l,Code2) from world.Country 153 Sunday, August 21, 11
  • 202. piping the result back to mysql echo "select concat_ws('|', $( mysql -NB -e 'select group_concat(column_name) from information_schema.columns where table_name="Country" and table_schema="world"')) as line from world.Country" | mysql | head -n 4 line AFG|Afghanistan|Asia|Southern and Central Asia|652090.00|1919| 22720000|45.9|5976.00|Afganistan/Afqanestan|Islamic Emirate| Mohammad Omar|1|AF NLD|Netherlands|Europe|Western Europe|41526.00|1581|15864000| 78.3|371362.00|360478.00|Nederland|Constitutional Monarchy| Beatrix|5|NL ANT|Netherlands Antilles|North America|Caribbean|800.00|217000| 74.7|1941.00|Nederlandse Antillen|Nonmetropolitan Territory of 154 The Netherlands|Beatrix|33|AN Sunday, August 21, 11
  • 203. advanced command line techniques $_ dumping data 155 Sunday, August 21, 11
  • 204. advanced command line techniques $_ dumping data 155 Sunday, August 21, 11
  • 205. dumping a tab delimited data set # the naive way $ mysql -e "SELECT * into outfile '/tmp/city_data' from world.City" # it works only if: # - /tmp/city_data does not exist # - /tmp is world writable 156 Sunday, August 21, 11
  • 206. dumping a tab delimited data set $ mysql -B -N -e "SELECT * from world.City" > /tmp/city_data # it works always # if you omit the "-N" it also # includes a header 157 Sunday, August 21, 11
  • 207. dumping a CSV $ mysql -B -e "SELECT * from world.City" | perl -F"t" -lane 'print join ",", map {s/"/""/g; /^[d.]+$/ ? $_ : qq("$_")} @F ' > /tmp/city_data 158 Sunday, August 21, 11
  • 208. dumping a CSV $ mysql -B -e "SELECT * from world.City" | perl -F"t" -lane 'print join ",", splits the line by tabs, instead map {s/"/""/g; of the default whitespace /^[d.]+$/ ? $_ : qq("$_")} @F ' > /tmp/city_data 158 Sunday, August 21, 11
  • 209. advanced command line techniques script it 159 Sunday, August 21, 11
  • 210. use the mysql.sh script § The companion code for this tutorial § http://tinyurl.com/cli-tut-code-2010 § It will save you much typing § But use it at your own risk! 160 Sunday, August 21, 11
  • 211. Usage • download the script • load it $ source mysql.sh 161 Sunday, August 21, 11
  • 212. mysql.sh functions • my_batch "query" • returns the result of the query. • Without header • Without box $ my_batch "SELECT * FROM test.t1" 1 aaa 2 bbb 3 ccc 162 Sunday, August 21, 11
  • 213. mysql.sh functions • my_value "what" • returns a single value • e.g. $ my_value "version()" 5.1.49 $ my_value "@@server_id" 1 163 Sunday, August 21, 11
  • 214. mysql.sh functions • my_var "what" • returns the value of a given variable • e.g. $ my_var port 3306 $ my_var datadir /usr/local/mysql/data 164 Sunday, August 21, 11
  • 215. mysql.sh functions • my_status "what" • returns the value of a given status item • e.g. $ my_status com_select 2653 $ my_status connections 452 165 Sunday, August 21, 11
  • 216. mysql.sh functions • my_dump_dataset "query" [header] • returns the values of a given query separated by tabs • if a header is requested, it will be part of the result • e.g. $ my_dump_dataset "select * from world.City" | head -n 5 1 Kabul AFG Kabol 1780000 2 Qandahar AFG Qandahar 237500 3 Herat AFG Herat 186800 4 Mazar-e-Sharif AFG Balkh 127800 166 5 Amsterdam NLD Noord-Holland 731200 Sunday, August 21, 11
  • 217. mysql.sh functions • my_csv "query" [separator] • returns the values of a given query separated by commas, or by a given separator • e.g. $ my_csv 'select * from world.City' | head -n 3 "ID","Name","CountryCode","District"," Population" 1,"Kabul","AFG","Kabol",1780000 2,"Qandahar","AFG","Qandahar",237500 167 Sunday, August 21, 11
  • 218. inside the command line client handling :-) @ @ $_ output 168 Sunday, August 21, 11
  • 219. pager mysql> SELECT * FROM world.City; rec … rec … rec … 4000 + records unreadable 169 Sunday, August 21, 11
  • 220. pager mysql> pager less PAGER set to 'less' mysql> SELECT * FROM world.City; # [ records in a manageable window ] mysql> nopager PAGER set to stdout # back to normal 170 Sunday, August 21, 11
  • 221. More pager tricks mysql> pager vim - # like 'less', but you can also edit # the results and eventually save # them 171 Sunday, August 21, 11
  • 222. More pager tricks mysql> pager md5sum PAGER set to 'md5sum' mysql> select * from City; 5d17ffa50d6da200dee621823ade2543 - 4079 rows in set (0.01 sec) # produce a CRC for the result set # instead of displaying it. # Useful for data comparison. # (Thanks to Baron Schwartz 172 Sunday, August 21, 11
  • 223. Comparing data sets with md5sum mysql> select * from City; 5d17ffa50d6da200dee621823ade2543 - mysql> select * from City order by ID; 5d17ffa50d6da200dee621823ade2543 - mysql> select * from City order by name; 5ab980f5b69a6e65d3b8cd5a95ec94e0 - mysql> select * from City order by District; 2bf37cbe91b3ffeaebc8c4b6084b8784 - 173 Sunday, August 21, 11
  • 224. Comparing data sets with md5sum mysql> select * from City; 5d17ffa50d6da200dee621823ade2543 - mysql> select * from City order by ID; 5d17ffa50d6da200dee621823ade2543 - mysql> select * from City order by name; 5ab980f5b69a6e65d3b8cd5a95ec94e0 - mysql> select * from City order by District; 2bf37cbe91b3ffeaebc8c4b6084b8784 - 173 Sunday, August 21, 11
  • 225. More pager tricks mysql> pager cat > /tmp/t1.txt mysql> select "one" union select "two"; mysql> pager cat > /tmp/t2.txt mysql> select "one" union select "TWO"; mysql> nopager mysql> ! vimdiff -o /tmp/t[12].txt # see the difference between two # datasets 174 Sunday, August 21, 11
  • 227. logging sessions mysql> tee mylog.txt # logs everything that you see on # the screen. # your commands, the results, # warnings, error messages, and so on. mysql> notee # back to normal 176 Sunday, August 21, 11
  • 228. read more § http://datacharmer.blogspot.com Sunday, August 21, 11
  • 229. THANKS! ? Question time Comments on Twitter: @datacharmer This work is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported License. Sunday, August 21, 11
  • 230. to do § add dead languages § comparing Latin and ancient Greek to COBOL and Pascal § add new tricks § {x,y} expansion in bash § G in MySQL § Sunday, August 21, 11