经过mysqladmin远程管理mysql的方法,Tookit工具包之pt

 

MySQL Practice

MySQL
Documentation

MySQL Reference Manual
(5.6,
5.7)

 

在地面安装mysql的服务端,展开cmd,cd到mysql安装目录下的bin目录,bin目录中能够观望七个可实施文件,当中mysqladmin就是足以用来远程关闭mysql服务的。

Preface

Indexes (5.6, 5.7)

In this lesson we are going to unleash what may be the coolest feature
of the command line.It’s called I/O redirection.The “I/O” stands for
input/output and with this facility you can redirect the input and
output of commands to and from files,as well as connect multiple
commands together into powerful command pipelines.(管道)To show off
this facility,we will introduce the following commands:

mysqladmin的参数如下:

 

Example Databases

  • cat – Concatenate files
  • sort – Sort lines of text
  • uniq – Report or omit repeated lines
  • grep – Print lines matching a pattern
  • wc – Print newline,word,and byte counts for each file
  • head – Output the first part of a file
  • tail – Output the last part of a file
  • tee – Read from standard input and write to standard output and
    files

mysqladmin Ver 8.42 Distrib 5.5.2-m2, for Win32 on ia32
Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
This software comes with ABSOLUTELY NO WARRANTY. This is free
software,
and you are welcome to modify and redistribute it under the GPL license

    We are always obliged to analyze many
outputs generated by various tools directly even in flat text files in
server performance diagnosis.Further more,we need to compare the
differences depend on these results such as the output of “mysqladmin”
tool.

Employees Sample Database

https://github.com/datacharmer/test\_db

shell< mysql < employees.sql

Sakila Sample
Database


Standard input,output and errors

Administration program for the mysqld daemon.
Usage: mysqladmin [OPTIONS] command command….
-c, –count=# Number of iterations to make. This works with -i
(–sleep) only.
–debug-check Check memory and open file usage at exit .
–debug-info Print some debug info at exit.
-f, –force Don’t ask for confirmation on drop database; with
multiple commands, continue even if an error occurs.
-C, –compress Use compression in server/client protocol.
–character-sets-dir=name
Directory where character sets are.
–default-character-set=name
Set the default character set.
-?, –help Display this help and exit.
-h, –host=name Connect to host.
-b, –no-beep Turn off beep on error.
-p, –password[=name]
Password to use when connecting to server. If password is
not given it’s asked from the tty.
-W, –pipe Use named pipes to connect to server.
-P, –port=# Port number to use for connection or 0 for default to, in
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/services, built-in default (3306).
–protocol=name The protocol of connection (tcp,socket,pipe,memory).
-r, –relative Show difference between current and previous values when
used with -i. Currently works only with extended-status.
-O, –set-variable=name
Change the value of a variable. Please note that this
option is deprecated; you can set variables directly with
–variable-name=value.
–shared-memory-base-name=name
Base name of shared memory.
-s, –silent Silently exit if one can’t connect to server.
-S, –socket=name Socket file to use for connection.
-i, –sleep=# Execute commands again and again with a sleep between.
–ssl Enable SSL for connection (automatically enabled with
other flags). Disable with –skip-ssl.
–ssl-ca=name CA file in PEM format (check OpenSSL docs, implies
–ssl).
经过mysqladmin远程管理mysql的方法,Tookit工具包之pt。–ssl-capath=name CA directory (check OpenSSL docs, implies –ssl).
–ssl-cert=name X509 cert in PEM format (implies –ssl).
–ssl-cipher=name SSL cipher to use (implies –ssl).
–ssl-key=name X509 key in PEM format (implies –ssl).
–ssl-verify-server-cert
Verify server’s “Common Name” in its cert against
hostname used when connecting. This option is disabled by
default.
-u, –user=name User for login if not current user.
-v, –verbose Write more information.
-V, –version Output version information and exit.
-E, –vertical Print output vertically. Is similar to –relative, but
prints output vertically.
-w, –wait[=#] Wait and retry if connection is down.
–connect_timeout=#
–shutdown_timeout=#

 

Chapter 2 Installing and Upgrading MySQL (5.6, 5.7)

Many of the programs that we have used so far produce output of some
kind.This output often consists of two types.First,we have the program’s
results;that is,the data the program is designed to produce,and
second,we have status and error messages that tell us how the program is
getting along.If we look at a command like ls ,we can see that it
displays its results and its error messages on the screen.

Variables (–variable-name=value)
and boolean options {FALSE|TRUE} Value (after reading options)
——————————— —————————–
count 0
debug-check FALSE
debug-info FALSE
force FALSE
compress FALSE
character-sets-dir (No default value)
default-character-set auto
host (No default value)
no-beep FALSE
port 3306
relative FALSE
shared-memory-base-name (No default value)
socket (No default value)
sleep 0
ssl FALSE
ssl-ca (No default value)
ssl-capath (No default value)
ssl-cert (No default value)
ssl-cipher (No default value)
ssl-key (No default value)
ssl-verify-server-cert FALSE
user (No default value)
verbose FALSE
vertical FALSE
connect_timeout 43200
shutdown_timeout 3600

Introduce

2.5 Installing MySQL on Linux (5.6, 5.7)

Keeping with the Unix theme of “everything is a file,”programs such as
ls actually send their results to a special file called standard
output(often expressed as stdout) and their status messages to another
file called standard error(stderr).By default,both standard output and
standard error are linked to the screen and not saved into a disk
file.In addition,many programs take input from a facility called
standard input (stdin) which is,by default,attached to the keyboard.

Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf
F:\MySQL\my.ini F:\MySQL\my.cnf
The following groups are read: mysqladmin client
The following options may be given as the first argument:
–print-defaults Print the program argument list and exit
–no-defaults Don’t read default options from any options file
–defaults-file=# Only read default options from the given file #
–defaults-extra-file=# Read this file after the global files are read

 

2.5.1 Installing MySQL on Linux Using the MySQL Yum Repository (5.6, 5.7)

Download MySQL Yum
Repository

A Quick Guide to Using the MySQL Yum
Repository

install-mysql-yum-centos.sh

./install-mysql-yum-centos.sh centos6 mysql56

I/O redirection allows us to change where output goes and where input
come from.Normally,output goes to the screen and input comes from the
keyboard,but with I/O redirection,we can change that.

Where command is a one or more of: (Commands may be shortened)
create databasename Create a new database
debug Instruct server to write debug information to log
drop databasename Delete a database and all its tables
extended-status Gives an extended status message from the server
flush-hosts Flush all cached hosts
flush-logs Flush all logs
flush-status Clear status variables
flush-tables Flush all tables
flush-threads Flush the thread cache
flush-privileges Reload grant tables (same as reload)
kill id,id,… Kill mysql threads
password new-password Change old password to new-password, MySQL 4.1
hashing.
old-password new-password Change old password to new-password in old
format.

    pt-mext is tht very tool which can
help you to accomplish the work mentioned above 
easily.It can execute the command
which you specify then print the result side-by-side in one line.Not
only can it print results from a running program but also can it print
results from a flat text file.

2.5.3 Installing MySQL on Linux Using the MySQL APT Repository (5.6, 5.7)

Download MySQL APT
Repository

A Quick Guide to Using the MySQL APT
Repository

## Ubuntu 14.04/16.04/17.04, Debian 7.11/8.9/9.1 ##
$ wget https://repo.mysql.com//mysql-apt-config_0.8.7-1_all.deb
$ sudo dpkg -i mysql-apt-config_0.8.7-1_all.deb

## Configuring mysql-apt-config ##
# Ubuntu 16.04/17.04 only has MySQL >=5.7

$ sudo apt-get update
$ sudo apt-get install -y mysql-server

## Configuring mysql-community-server ##

## Switch to another supported major release series at any time ##
$ sudo dpkg-reconfigure mysql-apt-config
$ sudo apt-get update

 

ping Check if mysqld is alive
processlist Show list of active threads in server
reload Reload grant tables
refresh Flush all tables and close and open logfiles
shutdown Take server down
status Gives a short status message from the server
start-slave Start slave
stop-slave Stop slave
variables Prints variables available
version Get version info from server

 

2.10 Postinstallation Setup and Testing (5.6, 5.7)

Redirection standard output

此地大家只须要中间的-h
参数钦定远端主机,-u内定远端登陆用户,-p钦命供给使用密码验证
最终的授命部分,使用shutdown就可以
总体命令如下:
mysqladmin -h10.101.0.1 -uroot -p123456 shutdown

Procedure

2.10.1 Initializing the Data Directory (5.6, 5.7)

I/O redirection allows us to redefine where standard output goes.To
redirect standard output to another file besides the screen,we use the
“>” redirection operator followed by the name of the file.Why would
we want to do this?It’s often useful to store the output of a command in
a file.For example,we could tell the shell to send the output of the ls
command to the file ls-output.txt instead of the screen:

当然同理,能够远程推行ping processlist reload refresh shutdown status
start-slave stop-slave variables version等一声令下

 

MySQL 5.6

## CentOS 6.9/7.3 ##
mysql_install_db --user=mysql

mysql_install_db
— Initialize MySQL Data Directory

997755.com澳门葡京 1

您可能感兴趣的小说:

  • Linux中应用mysqladmin
    extended-status合营Linux命令查看MySQL运市场价格况
  • mysql
    DBA:mysqladmin常用命令总计
  • 动用mysqladmin检查评定MySQL运维处境的课程

Usage

MySQL 5.7

Here,we created a long listing of the /usr/bin directory and sent the
results to the file ls-output.txt.Let’s examine the redirected output of
the command:

1 pt-mext [OPTIONS] -- COMMAND
2.10.1.1 Initializing the Data Directory Manually Using mysqld
## CentOS 6.9/7.3 ##
$ mysqld --initialize-insecure --user=mysql

# Check whether the data directory is initialiazed.
$ ls -al /var/lib/mysql

997755.com澳门葡京 2

 

2.10.1.2 Initializing the Data Directory Manually Using mysql_install_db

Good;a nice,large,text file.If we look at the file with less,we will see
that the file ls-output.txt does indeed contain the results from our ls
command:

**Common Parameters**

2.10.2 Starting the Server (5.6, 5.7)

Start the server

## CentOS 6.9, Ubuntu 14.04, Debian 7.11/8.9(MySQL 5.6)/9.1(MySQL 5.6) ##
mysqld_safe --user=mysql &

## CentOS 6.9, Ubuntu 14.04/16.04/17.04, Debian 7.11/8.9/9.1 ##
service mysql start

## CentOS 7.3 ##
systemctl start mysqld

## Ubuntu 16.04/17.04, Debian 8.9/9.1 ##
systemctl start mysql

Shut down the server

## CentOS 6.9, Ubuntu 14.04/16.04/17.04, Debian 7.11/8.9/9.1 ##
mysqladmin -u root shutdown

## CentOS 6.9, Ubuntu 14.04/16.04/17.04, Debian 7.11/8.9/9.1 ##
service mysql stop

## CentOS 7.3 ##
systemctl stop mysqld

## Ubuntu 16.04/17.04, Debian 8.9/9.1 ##
systemctl stop mysql

mysqld_safe — MySQL Server Startup Script
(5.6,
5.7)

997755.com澳门葡京 3

1 --relative //Each column substracts the value of the column before it.

2.10.3 Testing the Server (5.6, 5.7)

Simple tests to check whether the server is up and responding to
connections

## CentOS 6.9/7.3, Ubuntu 14.04/16.04/17.04, Debian 7.11/8.9/9.1 ##
$ mysqladmin version
$ mysqladmin variables

Verify that you can retrieve information from the server

## CentOS 6.9/7.3, Ubuntu 14.04/16.04/17.04, Debian 7.11/8.9/9.1 ##
$ mysqlshow
$ mysqlshow mysql
$ mysql -e "SELECT User, Host, plugin FROM mysql.user" mysql

Now,let’s repeat our redirection test,but this time with a twist.(扭曲)
We’ll change the name of the directory to one that does not exist:

 

2.10.4 Securing the Initial MySQL Accounts (5.6, 5.7)

## CentOS 6.9/7.3, Ubuntu 14.04/16.04/17.04, Debian 7.11/8.9/9.1 ##
$ mysql_secure_installation

mysql_secure_installation — Improve MySQL Installation Security
(5.6,
5.7)


997755.com澳门葡京 4

Example

Chapter 3 Tutorial (5.6, 5.7)

We received an error message.This makes sense since(因为) we specified
the non-existent directory /bin/usr,but why was the error message
displayed on the screen rather than being redirectored to the file
ls-output.txt?The answer is that the ls program does not send its error
messages to standard output.Instead,like most well-written Unix
programs,it sends its error messages to standard error.Since we only
redirected standard output and not standard error,the error message was
still sent to the screen.We’ll see how to redirect standard error in
just a minute,but first,let’s look at what happened to our output file:

 

3.1 Connecting to and Disconnecting from the Server (5.6, 5.7)

$ mysql -h host -u user -p

If you are logging in on the same machine that MySQL is running on, you
can omit the host, and simply use the following:

$ mysql -u user -p

After you have connected successfully, you can disconnect any time by
typing QUIT (or \q) at the mysql> prompt:

mysql> QUIT

997755.com澳门葡京 5

Collect the global status of MySQL
with 1s interval and 3 times in all by mysqladmin.

3.4 Getting Information About Databases and Tables (5.6, 5.7)

You have previously seen SHOW DATABASES, which lists the databases
managed by the server. To find out which database is currently selected,
use the DATABASE() function:

mysql> SELECT DATABASE();

mysql> SHOW TABLES;

mysql> DESCRIBE pet;

!!!注意在此之前文件大小是9290一,未来是0了

 1 [root@zlm2 10:43:03 ~]
 2 #mysqladmin ext -i1 -c3 > mysqladmin.log
 3 
 4 [root@zlm2 10:43:16 ~]
 5 #ls -l
 6 total 2554836
 7 -rw-------.  1 root root       1431 Jul 16  2015 anaconda-ks.cfg
 8 -rwxr-xr-x   1 root root 2611024896 Jun 13 03:03 mysql-5.7.21-linux-glibc2.12-x86_64.tar
 9 -rw-r--r--   1 root root     108476 Jul 12 10:43 mysqladmin.log
10 -rwxr-xr-x   1 root root         54 Jun 13 04:16 mysqld.sh
11 -rwxr-xr-x   1 root root    5000812 Jun 26 08:59 percona-toolkit-3.0.4-1.el7.x86_64.rpm
12 drwxr-xr-x  13 root root       4096 Jul  4 03:21 sysbench-1.0

3.5 Using mysql in Batch Mode (5.6, 5.7)

$ mysql -h host -u user -p < batch-file

mysql> source filename;
mysql> \. filename

The file now has zero length!This is because,when we redirect output
with the “>” redirection operator,the destination file is always
rewritten from the beginning.Since our ls command generated(使形成)no
results and only an error message,the redirection operation started to
rewrite the file and then stopped because of the error,resulting in its
truncation(切断).In fact,if we ever need to actually truncate a file (or
create a new,empty file)we can use a trick(技巧) like this:

 

Chapter 4 MySQL Programs (5.6)

997755.com澳门葡京 6

**The
“mysqladmin.log” file contains all the output of the three times
individually.**

4.2 Using MySQL Programs (5.6)

Simply using the redirection operator with no command
preceding(在先的,前面的) it will truncate(把…截短,缩短) an
existing file or create a new,empty file.

 1 [root@zlm2 10:49:28 ~]
 2 #cat mysqladmin.log
 3 +-----------------------------------------------+--------------------------------------------------+
 4 | Variable_name                                 | Value                                            |
 5 +-----------------------------------------------+--------------------------------------------------+
 6 | Aborted_clients                               | 0                                                |
 7 | Aborted_connects                              | 0                                                |
 8 | Binlog_cache_disk_use                         | 0                                                |
 9 | Binlog_cache_use                              | 0                                                |
10 | Binlog_stmt_cache_disk_use                    | 0                                                |
11 | Binlog_stmt_cache_use                         | 0                                                |
12 | Bytes_received                                | 2142                                             |
13 | Bytes_sent                                    | 155447                                           |
14 | Com_admin_commands                            | 0                                                |
15 | Com_assign_to_keycache                        | 0                                                |
16 | Com_alter_db                                  | 0                                                |
17 | Com_alter_db_upgrade                          | 0                                                |
18 ...
19 
20 +-----------------------------------------------+--------------------------------------------------+
21 | Variable_name                                 | Value                                            |
22 +-----------------------------------------------+--------------------------------------------------+
23 | Aborted_clients                               | 0                                                |
24 | Aborted_connects                              | 0                                                |
25 | Binlog_cache_disk_use                         | 0                                                |
26 | Binlog_cache_use                              | 0                                                |
27 | Binlog_stmt_cache_disk_use                    | 0                                                |
28 | Binlog_stmt_cache_use                         | 0                                                |
29 | Bytes_received                                | 2177                                             |
30 | Bytes_sent                                    | 165275                                           |
31 | Com_admin_commands                            | 0                                                |
32 | Com_assign_to_keycache                        | 0                                                |
33 | Com_alter_db                                  | 0                                                |
34 | Com_alter_db_upgrade                          | 0                                                |
35 ...
36 
37 +-----------------------------------------------+--------------------------------------------------+
38 | Variable_name                                 | Value                                            |
39 +-----------------------------------------------+--------------------------------------------------+
40 | Aborted_clients                               | 0                                                |
41 | Aborted_connects                              | 0                                                |
42 | Binlog_cache_disk_use                         | 0                                                |
43 | Binlog_cache_use                              | 0                                                |
44 | Binlog_stmt_cache_disk_use                    | 0                                                |
45 | Binlog_stmt_cache_use                         | 0                                                |
46 | Bytes_received                                | 2212                                             |
47 | Bytes_sent                                    | 175103                                           |
48 | Com_admin_commands                            | 0                                                |
49 | Com_assign_to_keycache                        | 0                                                |
50 | Com_alter_db                                  | 0                                                |
51 | Com_alter_db_upgrade                          | 0                                                |

4.2.2 Connecting to the MySQL Server (5.6)

$ mysql --host=localhost --user=myname --password mydb
$ mysql -h localhost -u myname -p mydb

You can specify connection parameters in the [client] section of an
option file. The relevant section of the file might look like this:

[client]
host=host_name
user=user_name
password=your_pass

So,how can we append redirected output to a file instead of overwriting
the file from the beginning?For that,we use the “>>” redirection
operator,like so:

 

4.2.6 Using Option Files (5.6)

To determine whether a program reads option files, invoke it with the
--help option. (For mysqld, use --verbose and --help.) If the
program reads option files, the help message indicates which files it
looks for and which option groups it recognizes.

File Name Purpose
/etc/my.cnf Global options
/etc/mysql/my.cnf Global options
SYSCONFDIR/my.cnf Global options
$MYSQL_HOME/my.cnf Server-specific options (server only)
defaults-extra-file The file specified with –defaults-extra-file, if any
~/.my.cnf User-specific options
~/.mylogin.cnf User-specific login path options (clients only)

Option Files Read on Unix and Unix-Like Systems

File Name Purpose
/etc/my.cnf Global options
/etc/mysql/my.cnf Global options
SYSCONFDIR/my.cnf Global options
$MYSQL_HOME/my.cnf Server-specific options (server only)
defaults-extra-file The file specified with –defaults-extra-file, if any
~/.my.cnf User-specific options
~/.mylogin.cnf User-specific login path options (clients only)

997755.com澳门葡京 7

**Execute pt-mext to print them again
with the “mysqladmin.log” file.**

4.2.7 Command-Line Options that Affect Option-File Handling (5.6)

Most MySQL programs that support option files handle the following
options. Because these options affect option-file handling, they must be
given on the command line and not in an option file. To work properly,
each of these options must be given before other options.

  • --defaults-extra-file=file_name

  • --defaults-file=file_name

  • --no-defaults

Using the “>>” operator will result in the output being appended
to file,If the file does not exist,it is created just as though the
“>” operator had been used.Let’s put it to the test:

 1 [root@zlm2 10:56:56 ~]
 2 #pt-mext -- cat mysqladmin.log
 3 Aborted_clients                               0       0
 4 Aborted_connects                              0       0
 5 Binlog_cache_disk_use                         0       0
 6 Binlog_cache_use                              0       0
 7 Binlog_stmt_cache_disk_use                    0       0
 8 Binlog_stmt_cache_use                         0       0
 9 Bytes_received                             2142    2177
10 Bytes_sent                               155447  165275
11 Com_admin_commands                            0       0
12 Com_alter_db                                  0       0
13 Com_alter_db_upgrade                          0       0
14 ...
15 
16 //pt-mext arranges the results of those three times side-by-side and print them.
17 //The first column shows the first collected result and the second column shows the second one.
18 //The number of columns is n-1(n is the collection times here).

4.2.8 Using Options to Set Program Variables (5.6)

Many MySQL programs have internal variables that can be set at runtime
using the SET statement.

Most of these program variables also can be set at server startup by
using the same syntax that applies to specifying program options.

$ mysql --max_allowed_packet=16777216
$ mysql --max_allowed_packet=16M

997755.com澳门葡京 8

 

4.3 MySQL Server and Server-Startup Programs (5.6)

We repeated the command three times resulting in an output file three
times as large.

**Specify the “–relative” option to get
the differential data.**

4.3.1 mysqld — The MySQL Server (5.6)

mysqld, also known as MySQL Server, is the main program that does most
of the work in a MySQL installation. MySQL Server manages access to the
MySQL data directory that contains databases and tables. The data
directory is also the default location for other information such as log
files and status files.

The mysqld program has many options that can be specified at startup.
For a complete list of options, run this command:

$ mysqld --verbose --help

 

 1 [root@zlm2 11:05:50 ~]
 2 #pt-mext --relative -- cat mysqladmin.log
 3 Aborted_clients                               0       0
 4 Aborted_connects                              0       0
 5 Binlog_cache_disk_use                         0       0
 6 Binlog_cache_use                              0       0
 7 Binlog_stmt_cache_disk_use                    0       0
 8 Binlog_stmt_cache_use                         0       0
 9 Bytes_received                             2142      35 //2277-2142=35
10 Bytes_sent                               155447    9828 //165275-155447=9828
11 Com_admin_commands                            0       0
12 Com_alter_db                                  0       0
13 Com_alter_db_upgrade                          0       0
14 
15 //Differential data is more distinct for us to know about the variation of performance.
16 //Even though we use "--relative" option,there're still two columns here.

4.3.2 mysqld_safe — MySQL Server Startup Script (5.6)

mysqld_safe reads all options from the [mysqld], [server], and
[mysqld_safe] sections in option files.

Format Description
–basedir Path to MySQL installation directory
–datadir Path to data directory
–defaults-extra-file Read named option file in addition to usual option files
–defaults-file Read only named option file
–help Display help message and exit
–log-error Write error log to named file
–no-defaults Read no option files
–pid-file Path name of server process ID file
–port Port number on which to listen for TCP/IP connections
–socket Socket file on which to listen for Unix socket connections
–user Run mysqld as user having name user_name or numeric user ID user_id

mysqld_safe Options

Format Description
–basedir Path to MySQL installation directory
–datadir Path to data directory
–defaults-extra-file Read named option file in addition to usual option files
–defaults-file Read only named option file
–help Display help message and exit
–log-error Write error log to named file
–no-defaults Read no option files
–pid-file Path name of server process ID file
–port Port number on which to listen for TCP/IP connections
–socket Socket file on which to listen for Unix socket connections
–user Run mysqld as user having name user_name or numeric user ID user_id

Redirect standard error

 

4.4 MySQL Installation-Related Programs (5.6)

Redirecting standard error lacks the ease of a dedicated redirection
operator.To redirect standard error we must refer to its file
descriptor.A program can produce output on any of several numbered file
streams.While we have referred to the first three of these file streams
as standard input,output and error,the shell references them internally
as file descriptiors zero,one and two,respectively.(分别地)

**Execute pt-mext without flat text
file.**

4.4.3 mysql_install_db — Initialize MySQL Data Directory (5.6)

As of MySQL 5.6.8, on Unix platforms, mysql_install_db creates a
default option file named my.cnf in the base installation directory.
This file is created from a template included in the distribution
package named my-default.cnf. You can find the template in or under
the base installation directory. When started using mysqld_safe, the
server uses my.cnf file by default. If my.cnf already exists,
mysql_install_db assumes it to be in use and writes a new file named
my-new.cnf instead.

mysql_install_db Options

Format Description
–basedir Path to base directory
–datadir Path to data directory
–defaults-extra-file Read named option file in addition to usual option files
–defaults-file Read only named option file
–force Run even if DNS does not work
–help Display help message and exit
–keep-my-cnf Keep existing my.cnf file, do not create new one
–no-defaults Read no option files
–skip-name-resolve Use IP addresses rather than host names in grant tables
–user System login user under which to execute mysqld

The shell provides a notation for redirecting files using the file
descriptor number.Since standard error is the same as file descriptor
number two,we can redirect standard error with this notation:

 1 [root@zlm2 11:07:16 ~]
 2 #pt-mext -r -- mysqladmin ext -i1 -c3
 3 Aborted_clients                               0       0
 4 Aborted_connects                              0       0
 5 Binlog_cache_disk_use                         0       0
 6 Binlog_cache_use                              0       0
 7 Binlog_stmt_cache_disk_use                    0       0
 8 Binlog_stmt_cache_use                         0       0
 9 Bytes_received                             2453      35
10 Bytes_sent                               185024    9828
11 Com_admin_commands                            0       0
12 Com_alter_db                                  0       0
13 Com_alter_db_upgrade                          0       0
14 ...
15 
16 [root@zlm2 11:13:28 ~]
17 #pt-mext -- mysqladmin ext -i1 -c3
18 Aborted_clients                               0       0
19 Aborted_connects                              0       0
20 Binlog_cache_disk_use                         0       0
21 Binlog_cache_use                              0       0
22 Binlog_stmt_cache_disk_use                    0       0
23 Binlog_stmt_cache_use                         0       0
24 Bytes_received                             2764    2799
25 Bytes_sent                               214601  224429
26 Com_admin_commands                            0       0
27 Com_alter_db                                  0       0
28 Com_alter_db_upgrade                          0       0
29 ...

4.4.5 mysql_secure_installation — Improve MySQL Installation Security (5.6)

$ mysql_secure_installation

 997755.com澳门葡京 9

 

4.5 MySQL Client Programs (5.6)

 

Summary

4.5.1 mysql — The MySQL Command-Line Tool (5.6)

$ mysql --user=user_name --password db_name

$ mysql db_name < script.sql > output.tab

Redirect standard output and error to a single file

  • pt-mext
    has only three options and it is rather easy to use.
  • pt-mext
    is a useful tool in anaylzing differential data of 
    global status of 
    MySQL.
  • pt-mext
    can be used not not only in “mysqladmin” program but also
    others.
4.5.1.1 mysql Options (5.6)

mysql supports the following options, which can be specified on the
command line or in the [mysql] and [client] groups of an option
file.

Format Description
–database The database to use
–defaults-extra-file Read named option file in addition to usual option files
–defaults-file Read only named option file
–execute Execute the statement and quit
–help Display help message and exit
–host Connect to MySQL server on given host
–no-defaults Read no option files
–password Password to use when connecting to server
–port TCP/IP port number to use for connection
–socket For connections to localhost, the Unix socket file or Windows named pipe to use
–user MySQL user name to use when connecting to server
–version Display version information and exit

There are cases in which we may wish to capture all of the output of a
command to a single file.To do this,we must redirect both standard
output and standard error at the same time.There are two ways to do
this.First the traditional way,which works with old version of the
shell:

 

4.5.1.2 mysql Commands (5.6)
mysql> help

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear command.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
exit      (\q) Exit mysql. Same as quit.
help      (\h) Display this help.
quit      (\q) Quit mysql.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
system    (\!) Execute a system shell command.
use       (\u) Use another database. Takes database name as argument.

For server side help, type 'help contents'

997755.com澳门葡京 10

4.5.1.3 mysql Logging (5.6)

On Unix, the mysql client logs statements executed interactively to a
history file. By default, this file is named .mysql_history in your
home directory. To specify a different file, set the value of the
MYSQL_HISTFILE environment variable.

Using this method,we perform two redirections.First we redirect standard
output to the file ls-output.txt and then we redirect file descriptor
two (standard error) to file descriptor one (standard output) using the
notation 2>&1.

4.5.1.4 mysql Server-Side Help (5.6)
mysql> help contents
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the
following categories:
   Account Management
   Administration
   Data Definition
   Data Manipulation
   Data Types
   Functions
   Functions and Modifiers for Use with GROUP BY
   Geographic Features
   Language Structure
   Plugins
   Storage Engines
   Stored Routines
   Table Maintenance
   Transactions
   Triggers

Notice that the order of the redirections is significant.The redirection
of standard error must always occur after redirecting standard output or
it doesn’t work.In the example above,

4.5.1.5 Executing SQL Statements from a Text File (5.6)
$ mysql db_name < text_file

mysql> source file_name
mysql> \. file_name

997755.com澳门葡京 11

4.5.2 mysqladmin — Client for Administering a MySQL Server (5.6)

$ mysqladmin [options] command [command-arg] [command [command-arg]] ...
Format Description
create db_name Create a new database named db_name.
drop db_name Delete the database named db_name and all its tables.
extended-status Display the server status variables and their values.
flush-privileges Reload the grant tables (same as reload).
ping Check whether the server is available.
processlist Show a list of active server threads.
reload Reload the grant tables.
shutdown Stop the server.
start-slave Start replication on a slave server.
status Display a short server status message.
stop-slave Stop replication on a slave server.
variables Display the server system variables and their values.
version Display version information from the server.

 

4.5.4 mysqldump — A Database Backup Program (5.6)

To make a backup of an entire database:

$ mysqldump db_name > backup-file.sql

To load the dump file back into the server:

$ mysql db_name < backup-file.sql

Another way to reload the dump file:

$ mysql -e "source /path-to-backup/backup-file.sql" db_name

mysqldump is also very useful for populating databases by copying data
from one MySQL server to another:

$ mysqldump --opt db_name | mysql --host=remote_host -C db_name

You can dump several databases with one command:

$ mysqldump --databases db_name1 [db_name2 ...] > my_databases.sql

To dump all databases, use the --all-databases option:

$ mysqldump --all-databases > all_databases.sql

深感这里>&一有未有不影响

4.5.6 mysqlshow — Display Database, Table, and Column Information (5.6)

The mysqlshow client can be used to quickly see which databases exist,
their tables, or a table’s columns or indexes.

$ mysqlshow [options] [db_name [tbl_name [col_name]]]

 redirects standard error to the file ls-output.txt,but if the order is
changed to 

4.6 MySQL Administrative and Utility Programs (5.6)

997755.com澳门葡京 12

4.6.8 mysqlbinlog — Utility for Processing Binary Log Files (5.6)

The server’s binary log consists of files containing “events” that
describe modifications to database contents. The server writes these
files in binary format. To display their contents in text format, use
the mysqlbinlog utility. You can also use mysqlbinlog to display the
contents of relay log files written by a slave server in a replication
setup because relay logs have the same format as binary logs.

$ mysqlbinlog [options] log_file ...

standard error is directed to the screen.

4.6.9 mysqldumpslow — Summarize Slow Query Log Files (5.6)

The MySQL slow query log contains information about queries that take a
long time to execute. mysqldumpslow parses MySQL slow query log files
and prints a summary of their contents.

$ mysqldumpslow [options] [log_file ...]

Recent versions of bash provide a second,more
streamlined(经过简化以改正功用的) method for performing this combined
redirection:

4.9 MySQL Program Environment Variables (5.6)

Variable Description
MYSQL_HISTFILE The path to the mysql history file. If this variable is set, its value overrides the default for $HOME/.mysql_history.
MYSQL_HISTIGNORE Patterns specifying statements not to log to $HOME/.mysql_history.
MYSQL_HOME The path to the directory in which the server-specific my.cnf file resides.
MYSQL_HOST The default host name used by the mysql command-line client.

997755.com澳门葡京 13

Chapter 5 MySQL Server Administration (5.6, 5.7)

 

5.1 The MySQL Server (5.6, 5.7)

Hand unnecessary output

5.1.1 Configuring the Server (5.6, 5.7)

To determine the command option and system variable values used by the
server, execute this command:

$ mysqld --verbose --help

To see the current system variable values used by the server as it runs,
connect to it and execute this statement:

mysql> SHOW VARIABLES;

To see some statistical and status indicators for a running server,
execute this statement:

mysql> SHOW STATUS;

System variable and status information also is available using the
mysqladmin command:

$ mysqladmin variables
$ mysqladmin extended-status

Sometime “silence is golden,” and we don’t want output from a command,we
just want to throw it away.This applies particularly to error and status
messages.The system provides a way to do this by redirecting output to a
special file called “/dev/null” .This file is a system device called a
bit bucket(位存储桶) which accepts input and does nothing with it.To
suppress error message from a command,we do this:

5.1.2 Server Configuration Defaults (5.6, 5.7)

997755.com澳门葡京 14

5.1.3 Server Option and Variable Reference (5.6, 5.7)

 

5.1.4 Server Command Options (5.6, 5.7)

$ mysqld --verbose --help

 /dev/null in Unix Culture

5.1.5 Server System Variables (5.6, 5.7)

The bit bucket is an ancient(古代的,古老的,过时的,老人,古代人) Unix
concept and due to its universality(普遍性),has appeared in many parts
of Unix culture.When someone says he/she is sending your comments to
/dev/null,now you know what it means.For more examples,see the Wikipedia
article on “/dev/null”.

5.1.6 Using System Variables (5.6, 5.7)

SET Syntax for Variable Assignment
(5.6,
5.7)

SHOW VARIABLES Syntax
(5.6,
5.7)

To display system variable names and values, use the SHOW VARIABLES
statement:

mysql> SHOW VARIABLES;

With a LIKE clause, the statement displays only those variables that
match the pattern. To obtain a specific variable name, use a LIKE
clause as shown:

mysql> SHOW VARIABLES LIKE 'max_join_size';
mysql> SHOW SESSION VARIABLES LIKE 'max_join_size';

To get a list of variables whose name match a pattern, use the %
wildcard character in a LIKE clause:

mysql> SHOW VARIABLES LIKE '%size%';
mysql> SHOW GLOBAL VARIABLES LIKE '%size%';

 

5.1.6.2 Dynamic System Variables (5.6, 5.7)

Redirect standard input

5.1.7 Server Status Variables (5.6, 5.7)

mysql> SHOW GLOBAL STATUS;

Many status variables are reset to 0 by the FLUSH STATUS statement.

Up to now(到明日归西),we haven’t encountered(蒙受) any commands that
make use of standard input (actually we have,but we’ll reveal(表露) that
surprise a little bit later),so we need to introduce one.

5.2 The MySQL Data Directory (5.6, 5.7)

cat – connect files

5.3 The mysql System Database (5.6, 5.7)

The cat commands reads one or more files and copies them to standard
output like so;

5.4 MySQL Server Logs (5.6, 5.7)

997755.com澳门葡京 15

5.4.1 Selecting General Query and Slow Query Log Output Destinations (5.6, 5.7)

In most cases,you can think of cat as being analogous(相似的) to the
TYPE command in DOS.You can use it to display files without paging,for
example:

5.4.2 The Error Log (5.6, 5.7)

997755.com澳门葡京 16

5.4.3 The General Query Log (5.6, 5.7)

will display the contents of the file ls-output.txt.cat is often used to
display sort text files.Since cat can accept more than one file as an
argument,it can also be used to join files together.Say we have
downloaded a large file that has been split into multiple parts
(multimedia files are often split this way on USENET),and we want to
join them back together.If the files were named:

5.4.4 The Binary Log (5.6, 5.7)

log-bin max_binlog_size binlog-do-db binlog-ignore-db
replicate-do-db replicate-ignore-db sync_binlog

mysqlbinlog(5.6,
5.7)
— Utility for Processing Binary Log Files

movie.mpeg.001 movie.mpeg.002 … movie.mpeg.099

5.4.4.1 Binary Logging Formats (5.6, 5.7)

--binlog-format={ROW|STATEMENT|MIXED}

we could join them back together with this command:

5.4.4.2 Setting The Binary Log Format (5.6, 5.7)

The logging format also can be switched at runtime. To specify the
format globally for all clients, set the global value of the
binlog_format system variable:

mysql> SET GLOBAL binlog_format = 'STATEMENT';
mysql> SET GLOBAL binlog_format = 'ROW';
mysql> SET GLOBAL binlog_format = 'MIXED';

An individual client can control the logging format for its own
statements by setting the session value of binlog_format:

mysql> SET SESSION binlog_format = 'STATEMENT';
mysql> SET SESSION binlog_format = 'ROW';
mysql> SET SESSION binlog_format = 'MIXED';

997755.com澳门葡京 17

5.4.5 The Slow Query Log (5.6, 5.7)

long_query_time slow_query_log slow_query_log_file log-output

mysqldumpslow(5.6,
5.7)
— Summarize Slow Query Log Files

Since wildcards always expand in sorted order,the arguments will be
arranged in the correct order.

5.4.7 Server Log Maintenance (5.6, 5.7)


This is all well and good,but what does this have to do with standard
input?Noting yet,but let’s try something else.What happens if we type
“”cat” with no arguments:

Chapter 6 Security

997755.com澳门葡京 18

6.2 The MySQL Access Privilege System (5.6, 5.7)

Nothing happens,it just sits there like it’s hung.It may seem that
way,but it’s really doing exactly what it’s supposed to.

6.2.1 Privileges Provided by MySQL (5.6, 5.7)

If cat is not given any arguments,it reads from standard input and since
(又因为)standard input is,by default,attached to the keyboard,it’s
waiting for us to type something!Try this:

6.2.3 Specifying Account Names (5.6, 5.7)

 997755.com澳门葡京 19

6.2.6 When Privilege Changes Take Effect (5.6, 5.7)

To tell the server to reload the grant tables, perform a
flush-privileges operation. This can be done by issuing a
FLUSH PRIVILEGES statement or by executing a
mysqladmin flush-privileges or mysqladmin reload command.

Next,type a Ctrl-d(i.e.,hold down the Ctrl key and press “d”)to tell cat
that it has reached end of file(EOF) on standard input:

6.3 MySQL User Account Management (5.6, 5.7)

997755.com澳门葡京 20

6.3.1 User Names and Passwords (5.6, 5.7)

MySQL stores accounts in the user table of the mysql system database.
An account is defined in terms of a user name and the client host or
hosts from which the user can connect to the server.

To connect to a MySQL server with a command-line client, specify user
name and password options as necessary for the account that you want to
use:

$ mysql --user=finley --password db_name

If you prefer short options, the command looks like this:

$ mysql -u finley -p db_name

If you omit the password value following the –password or -p option on
the command line (as just shown), the client prompts for one.
Alternatively, the password can be specified on the command line:

$ mysql --user=finley --password=password db_name
$ mysql -u finley -ppassword db_name

If you use the -p option, there must be no space between -p and the
following password value.

In the absence of filename arguments,cat copies standard input to
standard output,so we see our line of text repeated.We can use this
behavior to create short text files.Let’s say that we wanted to create a
file called”lazy_dog.txt” containing the text in our example.We would
do this:

6.3.2 Adding User Accounts (5.6, 5.7)

The following example uses CREATE USER and GRANT statements to set up
four accounts:

mysql> CREATE USER 'finley'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'finley'@'localhost'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'finley'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'finley'@'%'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'admin'@'localhost' IDENTIFIED BY 'admin_pass';
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
mysql> CREATE USER 'dummy'@'localhost';

To see the privileges for an account, use SHOW GRANTS:

mysql> SHOW GRANTS FOR 'admin'@'localhost';

To see nonprivilege properties for an account, use SHOW CREATE USER:

## MySQL 5.7 ##
mysql> SHOW CREATE USER 'admin'@'localhost'\G

The next examples create three accounts and grant them access to
specific databases. Each of them has a user name of custom and password
of obscure:

mysql> CREATE USER 'custom'@'localhost' IDENTIFIED BY 'obscure';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON bankaccount.*
    ->     TO 'custom'@'localhost';
mysql> CREATE USER 'custom'@'host47.example.com' IDENTIFIED BY 'obscure';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON expenses.*
    ->     TO 'custom'@'host47.example.com';
mysql> CREATE USER 'custom'@'%.example.com' IDENTIFIED BY 'obscure';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON customer.*
    ->     TO 'custom'@'%.example.com';

997755.com澳门葡京 21

6.3.3 Removing User Accounts (5.6, 5.7)

To remove an account, use the DROP USER statement. For example:

mysql> DROP USER 'jeffrey'@'localhost';

Type the comand followed by the text we want in to place in the
file.Remember to type Ctrl-d at the end.Using the command line,we have
implemented the world’s dumbest(dumb愚蠢的) word processor!To see our
results,we can use cat to copy the file to stdout again:

6.3.4 Setting Account Resource Limits (5.6, 5.7)

To establish resource limits for an account, use the GRANT statement.
Provide a WITH clause that names each resource to be limited. The
default value for each limit is zero (no limit). For example, to create
a new account that can access the customer database, but only in a
limited fashion, issue these statements:

mysql> CREATE USER 'francis'@'localhost' IDENTIFIED BY 'frank';
mysql> GRANT ALL ON customer.* TO 'francis'@'localhost'
    ->     WITH MAX_QUERIES_PER_HOUR 20
    ->          MAX_UPDATES_PER_HOUR 10
    ->          MAX_CONNECTIONS_PER_HOUR 5
    ->          MAX_USER_CONNECTIONS 2;

To modify limits for an existing account, use a GRANT USAGE statement at
the global level (ON *.*). The following statement changes the query
limit for francis to 100:

mysql> GRANT USAGE ON *.* TO 'francis'@'localhost'
    ->     WITH MAX_QUERIES_PER_HOUR 100;

The statement modifies only the limit value specified and leaves the
account otherwise unchanged.

To remove a limit, set its value to zero. For example, to remove the
limit on how many times per hour francis can connect, use this
statement:

mysql> GRANT USAGE ON *.* TO 'francis'@'localhost'
    ->     WITH MAX_CONNECTIONS_PER_HOUR 0;

997755.com澳门葡京 22

6.3.5 Assigning Account Passwords (5.6, 5.7)

To assign a password when you create a new account, use CREATE USER
and include an IDENTIFIED BY clause:

mysql> CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';

To assign or change a password for an existing account, use one of the
following methods:

Use SET PASSWORD with the PASSWORD() function:

## 5.6 ##
mysql> SET PASSWORD FOR 'jeffrey'@'localhost' = PASSWORD('mypass');

# If you are not connected as an anonymous user, you can change your own password by omitting the FOR clause:
mysql> SET PASSWORD = PASSWORD('mypass');

Use the ALTER USER statement with an IDENTIFIED BY clause:

## 5.7 ##
mysql> ALTER USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';

# If you are not connected as an anonymous user, you can change your own password without naming your own account literally:
mysql> ALTER USER USER() IDENTIFIED BY 'mypass';

Use a GRANT USAGE statement at the global level (ON *.*) to change
an account password without affecting the account’s current privileges:

## 5.6 ##
mysql> GRANT USAGE ON *.* TO 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';

To change an account password from the command line, use the mysqladmin
command:

$ mysqladmin -u user_name -h host_name password "new_password"

Now that we know how cat accepts standard input,in addition to filename
arguments,let’s try redirecting standard input:

6.3.6 Password Expiration and Sandbox Mode (5.6, 5.7)

To expire an account password, use the ALTER USER statement. For
example:

mysql> ALTER USER 'myuser'@'localhost' PASSWORD EXPIRE;

997755.com澳门葡京 23

Chapter 11 Data Types (5.6, 5.7)

有木有开掘那几个cat < lazy_dog.txt也就等于 cat lazy_dog.txt

Chapter 17 Replication (5.6)

Using the “<” redirection operator,we change the source of standard
input from the keyboard to the file lazy_dog.txt.We see that the result
is the same as passing a single filename argument.This is not
particularly useful compared to passing a filename argument,but it
serves to demonstrate(说明,论证,证明) using a file as a source of
standard input.Other commands make better use of standard input,as we
shall soon see.

Quick Start

  • Master

# my.cnf
[mysqld]
log-bin=mysql-bin
server-id=1

# Session 1
CREATE USER 'repl'@'%' IDENTIFIED BY '666666';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';

# Session 1
FLUSH TABLES WITH READ LOCK;

# Session 2
SHOW MASTER STATUS;

mysqldump --all-databases --master-data > dbdump.db

# Session 1
UNLOCK TABLES;
  • Slave

mysql < dbdump.db

CHANGE MASTER TO \
MASTER_HOST='128.199.177.76', \
MASTER_USER='repl', \
MASTER_PASSWORD='666666', \
MASTER_LOG_FILE='mysql-bin.000001', \
MASTER_LOG_POS=411;

START SLAVE;

SHOW SLAVE STATUS \G;

Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0

Before we move on,check out the man page for cat,as it has several
interesting options.

17.1 Replication Configuration (5.6)

 

17.1.1 How to Set Up Replication (5.6997755.com澳门葡京,)

 Pipeline

17.1.1.1 Setting the Replication Master Configuration (5.6)
# Master
[mysqld]
log-bin=mysql-bin
server-id=1

After making the changes, restart the server.

The ability of commands to read data from standard input and input and
send to standard output is utilized by a shell feature called
pipelines.Using the pipe operator “|” (vertical bar),the standard output
of one command can be piped into the standard input of another:

17.1.1.2 Setting the Replication Slave Configuration (5.6)
# Slave
[mysqld]
server-id=2

After making the changes, restart the server.

997755.com澳门葡京 24

17.1.1.3 Creating a User for Replication (5.6)
# Master
mysql> CREATE USER 'repl'@'%.mydomain.com' IDENTIFIED BY 'slavepass';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%.mydomain.com';

To fully demonstrate this,we are going to need some commands.Remember
how we said there was one we already knew that accepts standard input?
It’s less.We can use less to display,page-by-page,the output of any
command that sends its results to standard output:

17.1.1.4 Obtaining the Replication Master Binary Log Coordinates (5.6)

To obtain the master binary log coordinates, follow these steps:

Start a session on the master by connecting to it with the command-line
client, and flush all tables and block write statements by executing the
FLUSH TABLES WITH READ LOCK statement:

# Master
mysql> FLUSH TABLES WITH READ LOCK;

Warning
Leave the client from which you issued the FLUSH TABLES statement
running so that the read lock remains in effect. If you exit the
client, the lock is released.

In a different session on the master, use the SHOW MASTER STATUS
statement to determine the current binary log file name and position:

# Master
mysql> SHOW MASTER STATUS;

997755.com澳门葡京 25

17.1.1.5 Creating a Data Snapshot Using mysqldump (5.6)
# Master
mysqldump --all-databases --master-data > dbdump.db

# Master
mysql> UNLOCK TABLES;

This is extremely handy! Using this technique(技巧,技术),we can
conveniently(方便地) examine the output of any command that produces
standard output.

17.1.1.8 Setting Up Replication with Existing Data (5.6)
# Slave
mysql < fulldb.dump

# Slave
mysql> START SLAVE;

 

17.1.1.10 Setting the Master Configuration on the Slave (5.6)
mysql> CHANGE MASTER TO
    ->     MASTER_HOST='master_host_name',
    ->     MASTER_USER='replication_user_name',
    ->     MASTER_PASSWORD='replication_password',
    ->     MASTER_LOG_FILE='recorded_log_file_name',
    ->     MASTER_LOG_POS=recorded_log_position;

Filters

Pipelines are often used to perform complex operations on data.It is
possible to put several commands together into a pipeline.Frequently,the
commands used this way are referred to as filters.Filters take
input,change it somehow and then output it.The first one we will try is
sort.Imagine we wanted to make a combined list of all of the executable
programs in /bin and /usr/bin,put them in sorted order and view it:

997755.com澳门葡京 26

Since  we specified two directories(/bin and /usr/bin),the output of ls
would have consisted of two sorted lists,one for each directory.By
including sort in our pipeline,we changed the data to produce a
single,sorted list.

!!!!!!!这里有人只怕会有疑难,到底是先输出四个排序好的公文,然后再出口3个排序好的文件。仍然多个文本的始末结合在协同,然后再排序输出呢?经试验验证,答案是后者。

 

uniq – report or omit duplicates (报纸发表或删除重复行)

The uniq command is often used in conjunction with sort.uniq accepts a
sorted list of data from either standard input or a single filename
argument (see the uniq man page for details) and,by default,removes any
duplicates from the list.So,to make sure our list has no duplicates(that
is,any programs of the same name that appear in both the /bin and
/usr/bin directories) we will add uniq to our pipeline:

997755.com澳门葡京 27

插个嘴,这里的sort | uniq也可以用sort -u代替

In this example,we use uniq to remove any duplicates from the output of
the sort command.If we want to see the list of duplicates instead,we add
the “-d” option to uniq like so:

997755.com澳门葡京 28

 

wc – print lines,words,and bytes

The wc (word count) command is used to display the number of
lines,words,and bytes contained in files.For example:

997755.com澳门葡京 29

In this case it prints out three numbers:lines,words,and bytes contained
in ls-output.txt.Like our previous commands,if executed without command
line arguments,wc accepts standard input.The “-l” option limits its
output to only report lines. Adding it to a pipeline is a handy way to
count things.To see the number of programs we have in our sorted list,we
can do this:

 997755.com澳门葡京 30

 

grep – print  match lines (打印匹配行)

grep is a powerful program used to find text patterns within files.It’s
used like this;

997755.com澳门葡京 31

When grep encounters a “pattern ” in the file,it prints out the lines
containing it.The patterns that grep can match can be very
complex(复杂的),but for now we will concentrate(专注于,注意) on
simple text matches.We’ll cover the advanced patterns,called regular
expressions in a later chapter.

Let’s say(举例说,用作插入语) we want to find all the files in our
list of programs that had the word “zip” embedded(植入的,内含的) in the
name.Such a search might give us an idea of some of the programs on our
system that had something to do with file
compression.(那样贰个追寻,可能让我们领悟系统中的一些先后与公事减弱有涉嫌)We
would do this:

997755.com澳门葡京 32

There are a couple of handy options for grep:”-i” which causes grep to
ignore case when performing the search (normally searches are case
sensitive) and “-v” which tells grep to only print lines that do not
match the pattern.

 

head /tail – type head / tail part of the file

Sometimes you don’t want all of the output from a command.You may only
want the first few lines or the last few lines.The head command prints
the first ten lines of a file and the tail command prints the last ten
lines.By default,both commands print ten lines of text,but this can be
adjusted with the “-n” option:

997755.com澳门葡京 33

These can be used in pipelines as well:

997755.com澳门葡京 34

tail has an option which allows you to view files in
real-time(实时).This is useful for watching the progress of log files as
they are being written.In the following example,we will look at the
messages file in /var/log.Superuser privileges(特权) are required to do
this on some Linux distributions,since the /var/log/messages file may
contain security information:

997755.com澳门葡京 35

Using the “-f” option,tail continues to monitor(监测) the file and
when new lines are appended,they immediately appear on the display.This
continues until you type Ctrl-c.

 

tee – read standard input and copies it to both standard output

In keeping with our plumbing metaphor,(为了和管道隐喻保持1致),Linux
provides a command called tee which creates a “tee” fitting on our
pipe.The tee program reads standard input and copies it to both standard
output (allowing the data to continue down the pipeline) and to one or
more files.This is useful for capturing a pipeline’s contents  at an
intermediate stage of processing.Here we repeat one of our pipe.The tee
program reads standard input and copies it to both standard
output(allowing the data to continue down the pipeline) and to one or
more files.This is useful for capturing a pipeline’s contents at

an intermediate(中间的)stage (阶段) of processing.Here we repeat one
of our earlier examples,this time including tee to capture the entire
directory listing to the file ls.txt before grep filters the pipeline’s
contents:

997755.com澳门葡京 36

tee从/usr/bin读取数据,并同时输出到Stdout和文书ls.txt中

Sum up

As always,check out the documentation of each of the commands we have
covered in the chapter.We have only seen their most basic usage.They all
have a number of interesting options.As we gain Linux experience,we will
see that the redirection feature of the command line is extremely useful
for solving specialized problems.There are many commands that make use
of standard input and output,and almost  all command line programs use
standard error to display their informative messages.

Linux ls About Imagination

When I am asked to explain the difference between Windows and Linux,I
often use a toy analogy(比喻).

Windows is like a Game boy.You go to the store and buy one all shiny new
in the box.You take it home,turn it on and play with it.Pretty
graphics,cute sounds.After a while though,you get tired of the game that
came with it so you go back to the store and buy another one.This cycle
repeats over and over.Finally,you go back to the store and say to the
person behind the counter,”I want a game that does this!” only to be
told that no such game exists because there is no “market demand” for
it.Then you say,”But I only need to change this one thing!” The person
behind the counter says you can’t change it.The games are all sealed up
in their cartridges.You discover that your toy is limited to the games
that others have decided that you need and no more.

Linux,on the other hand,is like the world’s largest
Erector(建立者,安装工) Set.You open it up and it’s just a huge
collection of parts.A lot of steel(钢铁)
struts,screws,nuts,gears,pulleys,motors,and a few suggestions on what
to build.So you start to play with it.You build one of the suggestions
and then another.After a while you discover that you have your own ideas
of what to make.You don’t ever have to go back to the store,as you
already have everything you need.The Erector Set takes on the shape of
your imagination.It does what you want.

Your choice of toy is,of course,a personal thing,so which toy would you
find more satisfying?

  

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website