Examples of common Linux commands and Bash Shell scripts, bashshell

Source: Internet
Author: User
Tags echo command processing text

Examples of common Linux commands and Bash Shell scripts, bashshell
Summary

The Linux Command isText-based input/outputAccording to the simple functions, loose input, and rigorous output of the program mentioned in the Unix philosophy, various program combinations can have more powerful functions, the main reason for this flexibility is that Linux requires that the input and output of a program must adhere to the file stream format, that is, the text format, which is one of the core of the Linux system.

Bash, or Shell, is the default command line interpreter for mainstream Linux releases. It is a powerful tool, you can combine program commands supported by Linux to implement powerful functions. Similar to the bat file of the Window system, Bash has more powerful functions. Through Bash, you can implement automated program design, function execution, and even system startup, thanks to the Unix design philosophy.

This blog post is based on my experience and is only for your reference. If you have any omissions, please leave a message to correct them. Thank you ~


----------------------------------- LinuxCommand details-----------------------------------


Directory commands

DisplayFile details in the current directoryLsShow only file names,LlThat is'LS-alf'The alias of the command can be viewed through the alias | grep 'l' command:

king@king-desktop:~/test$ lst1  test1king@king-desktop:~/test$ lltotal 12drwxr-xr-x  3 king king 4096 2014-08-23 18:26 ./drwxr-xr-x 39 king king 4096 2014-08-23 18:26 ../-rw-r--r--  1 king king    0 2014-08-23 18:26 t1drwxr-xr-x  2 king king 4096 2014-08-23 18:26 test1/king@king-desktop:~/test$ alias | grep  'll'alias ll='ls -alF'

In addition, if you want to use the classic tree directory display, you can use the additional tree Command (non-Internal Command). The specific operation is as follows:-L 2 refers to the root directory of the current directory, display the directory structure to the second layer:

king@king-desktop:~$ treeThe program 'tree' is currently not installed.  You can install it by typing:sudo apt-get install treeking@king-desktop:~$ sudo apt-get installking@king-desktop:~/test$ tree -L 2.|-- t1`-- test1    `-- t21 directory, 2 files

Create and deleteDirectory operation, useMkdirAndRmdirTwo commands: for deletion, if the directory is not empty, you can useRm-rf DirNameTo achieve:


king@king-desktop:~/test$ lst1  test1king@king-desktop:~/test$ mkdir test2king@king-desktop:~/test$ rmdir test1rmdir: failed to remove `test1': Directory not emptyking@king-desktop:~/test$ rm -rf test1king@king-desktop:~/test$ lst1  test2king@king-desktop:~/test$ rmdir test2/king@king-desktop:~/test$ lst1

TarCommand usage

It is often used for packaging, compression, and decompression. Its usage is related to parameters. c Indicates packaging, x indicates extraction, z indicates gzip compression, and j indicates bzip compression, v shows the decompression process. C indicates the directory to be extracted. Package directory test1. Pay attention to the following Parameter order and display the package name.

King @ king-desktop :~ /Test $ tar-cvf test.tar test1/test1/test1/t2king @ king-desktop :~ /Test $ lst1 test1 test.tar extracts the packaged files to the specified directory, and-C implements king @ king-desktop :~ /Test $ tar-xvf test.tar-C./test1/test1/test1/t2king @ king-desktop :~ /Test $ ls./test1/t2 test1gzip compression and decompression king @ king-desktop :~ /Test $ tar-czvf test.tar.gz test1/king @ king-desktop :~ /Test $ tar-xzvf test.tar.gz bzip2 compression and decompression king @ king-desktop :~ /Test $ tar-cjvf test.tar. bz test1/tar-xjvf test.tar. bz test1/


File-related


DisplayFile Content

IncludingCat, more, less, head, tail, nlAnd other internal commands can be implemented, but slightly different

CatOutput files in series to stdout, which is usually output on the terminal. Common parameters include-n. Similar to nl, the function outputs row numbers simultaneously.

MoreIt can be used to browse the content of a file that exceeds one page or the display length of the terminal. The Blank Space key is used to flip the page. The Enter key can be viewed, the Q key is exited, and the text is displayed on the terminal.

LessIt can be used to browse the content of a file that exceeds one page or the display length of the terminal. You can flip the page through the space bar key. The Enter key can be viewed. the up and down arrows can forward or backward. The Q key exits, the text is displayed in standalone mode.

HeadFollowed by the-n 10 parameter. Of course, 10 can be changed. It refers to the first 10 lines of the displayed text.

TailThe following parameter-n 10, same as above, refers to the last 10 lines of the displayed text

NlSimilar to cat-n

king@king-desktop:~/test$ cat t1helloworld!!!ENDgujinjinking@king-desktop:~/test$ head -n 1 t1helloking@king-desktop:~/test$ tail -n 2 t1ENDgujinjinking@king-desktop:~/test$ nl t1     1hello     2world     3!!!            4END     5gujinjinking@king-desktop:~/test$ cat -n t1     1hello     2world     3!!!     4     5END     6gujinjinking@king-desktop:~/test$ more t1helloworld!!!ENDgujinjin

Text StreamProcessing and use

Text Stream mode is one of the core concepts of Linux. Therefore, commands can be combined to form more powerful functions. There are many commands for processing text. Here I will mainly introduceWhat I think of nowSorry for the shortage!

Here we will mention the awk command, namely the text processor, which is quite powerful and amazing. It was developed by the three digits A, W, and K of Bell Labs. It is quite easy to get started, here is an article published by instructor Chen Hao on CoolShell.cn. The URL is as follows. If you are interested, see:

Http://coolshell.cn/articles/9070.html

Special symbols introduce "|" pipeline operator, connect the output of one program and the input path ">" ">" redirection of another program, and output to the specified file, the difference is that the former outputs and covers the original content of the file, and the latter outputs are added to the end of the file grep (global search regular expression (RE) and print out the line ), parameter-o indicates that only matching objects are output, and the complete line is not output. Example: Output IP address king @ king-desktop :~ /Test $ ifconfig | grep-o '[0-9] \ {1, 3 \}\. [0-9] \ {1, 3 \}\. [0-9] \ {1, 3 \}\. [0-9] \ {192 \} '2017. 168.229.200192.168.229.255425255.0127.0.0.1255.0.0.0cut, as the name suggests, will remove the input text and output an example, segment the ip address, and save the output to the ip address. description of log File parameters:-s does not output rows that do not contain the specified delimiter.-d specifies the delimiter and-f outputs the specified segment. Multiple lines can be output, for example,-f1, 3: Output 1, 3 segments king @ king-desktop :~ /Test $ cat ip. log | cut-s-d. -f1192192255425255sort: sorting. Here, two parameters are commonly used:-n is sorted based on the value size, generally in ascending order;-r is reversed, that is, there is a difference between adding n to reverse and not adding n, to demonstrate this difference. log is slightly modified. Pay attention to the difference, that is, the difference between the value processing and string processing: king @ king-desktop :~ /Test $ cat ip. log | cut-s-d.-f1 | sort12719219220255255king @ king-desktop :~ /Test $ cat ip. log | cut-s-d.-f1 | sort-n20127192192255255king @ king-desktop :~ /Test $ cat ip. log | cut-s-d. -f1 | sort-nr25525519219212720uniq is unique. Here, a common parameter-c is used for counting. Here, king @ king-desktop with the same Upper and Lower rows :~ /Test $ cat ip. log | cut-s-d. -f1 | sort | uniq-c 1 127 2 192 1 20 2 255awk usage preliminary,-F followed by the separator, $1 represents the first segment. For more information about the usage, see the connection described above. King @ king-desktop :~ /Test $ awk-F. '$1> 127 & $1 <255 {print $0}' ip. log 192.168.229.200192.168.229.255


Text processing example

Count the top 10 commands with the maximum number of historical commands used

king@king-desktop:~/test$ history | awk '{print $2}' | sort | uniq -c | sort -nr | head -n 10    255 ls    168 clear     79 cd     64 history     60 sh     48 sudo     46 cat     22 vim     20 clea     19 tree

Hahaha, what did I find? clea has 20 times. It can be seen that the clear command is often wrong ~



Permission-related

The permission management system is perfect in Linux, which is one of the reasons why Linux is rarely attacked by hackers. Three commonly used commands are chmod, chown, and chgrp for modifying edge file permissions.

Chmod changes file permissions, which are generally divided into readable, writable, and executable types, namely r-4, w-2, x-1,--0, it can be used in combination with the u-User, g-Group, o-Other, and a-All User groups of the file owner. The following three commands are equivalent to king @ king-desktop :~ /Test/test1 $ chmod ugo = rwx t2king @ king-desktop :~ /Test/test1 $ chmod a = rwx t2king @ king-desktop :~ /Test/test1 $ chmod 777 t2king @ king-desktop :~ /Test/test1 $ ll t2-rwxrwxrwx 1 king 10240 t2 * chown change the file owner, or change the user group king @ king-desktop :~ /Test/test1 $ sudo chown root t2king @ king-desktop :~ /Test/test1 $ ll t2-rwxrwxrwx 1 root king 10240 t2 * king @ king-desktop :~ /Test/test1 $ sudo chown root: root t2king @ king-desktop :~ /Test/test1 $ ll t2-rwxrwxrwx 1 root 10240 t2 * chgrp :~ /Test/test1 $ sudo chgrp root t2king @ king-desktop :~ /Test/test1 $ ll t2-rwxrwxrwx 1 king root 10240 t2 *

Network Problems

Ifconfig: View network configuration information. netstat provides TCP connections, TCP and UDP listeners, process memory management, route table information, and port information. Common parameters-r outputs route table information and-I network interface information.-a displays all socketking @ king-desktop :~ /Test/test1 $ netstat-a | grep tcp | head-n 1tcp 0 0 0 *: ssh *: * LISTENlsof list open files to list open file tools in the current system, it is generally used under the root permission. For example, check the process information of port 80: root @ king-desktop :~ # Lsof-I: 80 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEapache2 987 root 3u IPv4 4423 0t0 TCP *: www (LISTEN) apache2 3899 www-data 3u IPv4 4423 0t0 TCP *: www (LISTEN) apache2 3900 www-data 3u IPv4 4423 0t0 TCP *: www (LISTEN) apache2 3901 www-data 3u IPv4 4423 0t0 TCP *: www (LISTEN) apache2 3902 www-data 3u IPv4 4423 0t0 TCP *: www (LISTEN) apache2 3903 www-data 3u IPv4 4423 0t0 TCP *: www (LISTEN) nc NetCat, a network tool with powerful functions, can be used for port monitoring parameter description:-4 only IPv4,-6 only IPv6,-v output execution process,-w allow latency (s ), -z only scans the listening daemon and does not send messages.-u UDP is TCPking @ king-desktop by default :~ $ Nc-v-w 2-z 192.168.229.200 76-80nc: connect to 192.168.229.200 port 76 (tcp) failed: Connection refusednc: connect to 192.168.229.200 port 77 (tcp) failed: Connection refusednc: connect to 192.168.229.200 port 78 (tcp) failed: Connection refusednc: connect to 192.168.229.200 port 79 (tcp) failed: Connection refusedConnection to 192.168.229.200 80 port [tcp/www] succeeded!

------------------------Bash ShellImplementation example------------------------

Here are a few examples of common Shell syntax.


View a specified string modified by an author within a specified time period

#!/bin/bashres=`ls -l | awk '$3=="king" && $6=="2014-08-23" && $7<"22:10" && NR!=1 {print $8}'`#echo $resfor var in $res;do        r=`cat ./$var | grep -n -w 'test' >> mod.log`        #echo $var        if [ $? -ne 0 ];then                echo "Execute CMD error!!!"                exit 1        fidoneexit 0king@king-desktop:~/Shell$ sudo sh p1.sh king@king-desktop:~/Shell$ cat mod.log 1:this is a test this is a test6:this is a test this is a test

Start a process and run it in the background.

#!/bin/bashDIR=/home/king/CPPFile/Socketecho $DIRif [ -e $DIR/server ];then        $DIR/server & > info.log 2>&1        if [ $? -ne 0 ];then                echo "Execute Wrong!"                exit 1        fi        sleep 2        pid=$!        echo $pid        kill -9 $pid        if [ $? -ne 0 ];then                echo "fail to kill pid"                exit 2        fifiexit 0king@king-desktop:~/CPPFile/Socket$ sudo sh test.sh /home/king/CPPFile/Socket16028



Linux Red Hat shell programming. sh and bash are used in the bin directory parser, And the bash file name used by the script is displayed.

For example, I hope you can understand it.
First, edit a script.
Vi bash. sh (the name can be obtained by yourself)
Content
#! /Bin/bash (the type of scripts declared in this file. bash is used here. If other languages are used, search for them by yourself)
Echo "hello world" (a simple output statement is written in the script)
Then exit EDIT: Save wq (if vi is not used, you may need to know how to edit the text)
Run bash. sh to check the output of hello world.
./This indicates the current directory. If you want to execute the script in this way, you need to grant the script execution permission.
Command is chmod + x bash. sh
Then cd to the current directory of the script. ls can be seen, and then execute./bash. sh to OK.
The above involves vi tools, basic command usage, bash, and permissions. You should learn these first.
Ps:./The file name no such file or direch may be because the file has no execution permission.

To import windows Data to linux, you can use hard disks, USB flash drives, and other tools to import data. samba works well in both windows and linux, and is a sharing method. You can refer to baidu and google to learn about how to use samba at half past one. We recommend that you learn about the basics of linux before learning a variety of services such as samba.

Shell script commands in linux

Basic knowledge about Shell scripts

Overview: shell is actually an interface between the kernel and the user,

Shell script

If there are a series of frequently used linux commands, you can store them in a file swollen. Shenll can read this file and execute the command. Such a file becomes a script file.

Execute shell scripts

To create a shell script, you need to use any editor such as vi to write it in a text file.

To use bash shell Lai to execute the script magic, the command is bash magic or./magic

Echo command:

Echo "this is an example of the echo command !"

The screen displays "this is an example of the echo command !"

# Symbol

Used to include annotation entries in shell scripts.

Echo "hello"

# This is a comment line. this wocould not produce any output!

Echo "world !"

The second line is an example of annotation. It will be ignored by shell without generating any messages.

Variable:

It can be created by simple assignment at any time.

Syntax:

<Variable name>-<value>

All variables in Linux are treated as strings.

Reference variable:

$ The symbol is used to reference the content of a variable.

Variable1 =1 {variable2}

Read value to variable

When executing a shell script, shell also allows you to directly read a value from the keyboard to the variable. You can also use the read command for this purpose.

$ Read fname

Local and global shell Variables

Local variable

When a shell is referenced, only the shell that creates it can know the existence of the variable.

Global Variables

Called a sub-shell

The variable created in shell is partial to the shell that creates it, unless the export command is used to indicate that it is global.

Environment variable:

You can customize the environment by changing the value of these variables.

Examples of environment variables are HOME, PATH, PS1, PS2, LOGNAME, SHLVL, and SHELL.

HOME variable

In Linux, each user has a directory called HOME.

After a user logs on, the corresponding HOME directory is displayed.

$ Echo $ HOME

PATH variable

Contains the path name of a directory that is bounded by a colon to facilitate the search of executable programs.

PS1 variable

The PS1 (Prompt String 1) variable contains the shell Prompt, $ symbol

$ PS1 = "HELLO>"

HELLO>

PS2 variable

... The remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.