"Bash treasure Chest" Linux shell learning

Source: Internet
Author: User


Shell Features--


Linux has a variety of shells to use, the default for Bash,bash has the following key features.



1. Command Memory Ability



Press the up and down keys on the command line to find a pre/Post input command. These commands are recorded in~/.bash_historythis file, which records all the commands that were run by the last login shell, and the commands that are currently running on the shell are temporarily in memory, and the commands are updated to the file after the system has been successfully unregistered. The history command can behistoryviewed by command, which can be used with an exclamation mark when running a history command again!, followed by the sequence number of the history command. Assuming multiple login bash, that is, when you open several bash forms. The last bash that was written out will overwrite the previous bash's history.



2. Tab key



When a partial command or file is not fully entered. PressTabthe key once to complete the command or file, press theTabkey two times to list all the available commands or files.






3. Command alias setting function



Use toaliasset a simple alias for a longer command.unaliascancel the settings, such as the following example:


$alias lm=‘ls -alt‘


The abovealiascommand sets the alias to be valid only for the current bash, and the alias will expire after bash exits, how can it be set once to be able to work forever in all bash? The method is to write the above alias Settings command to the~/.bashrcfile, the file read into the shell can use thesourcecommand, can also use句点, or restart the computer, so that once and for all.






4. Built-in command type



BytypeCommand We are able to know the type of a command. is a built-in command, an external command, or an alias.typeThe command itself is a built-in command.



typeOften three parameters are used to-tdisplay the command type, and the command-pfull path is displayed only if the command type is external.-adisplaysPATHAll command-related instruction information in the environment variable, including thealiasalias command.



5. Command Run



command to run the need to press theEnterkey, assuming that the command requires multiple lines of input, you canEnterimmediately before the key to\escape a character, there can be no space between.






6. Bash Environment



1) The path and command lookup are in a certain order, and their order is: relative or absolute paths run commands >aliascommands >builtincommands >$PATHThe first command found in order of environment variables.



2) We are able to define our own Linux login and welcome information. The configuration file/etc/issue/etc/motdis for and/etc/issue.netis provided to Telnet for this Telnet application.





Shell Variables--


As in other programming languages. The shell can also define its own variables, but there are certain rules, such as the following.



1, such as the common environment variablesPATH. The display of variables can be viewed by commands, and variables are signed before they are optionally enclosed in aecho$pair of curly braces.



2=. The variable is assigned by an equal sign, and cannot have spaces on either side.



3, the variable name can only be English or numeric, the opening character cannot be a number.



4, the variable content includes special characters. Escape characters can be\escaped. The special character in the double-such as$retains its original character, and the special word such as $ in the single-quote is an ordinary one, which is matched to the left-to-right.



5. When other commands are included in a string of commands. Other commands are able to use the anti-single-quote ' command ' or dollar-sign combined with parentheses$(命令), such that the command will be run first. Run the result as input information.



6. When the variable accumulates the content, it can be used"$Variable name "or $ {variable name}manipulated, for example:


$PATH="$PATH"xxx$PATH=${PATH}xxx


7. Variables need to be in the context of the sub-process,exportmaking it an environment variable.



Enter a subprocess to be able to use the Bash command when exiting using theexitcommand.



8. Use when canceling variablesunset.






9, environment variable view can useenvcommands, canexportalso use commands.setcommand to view all variables. Includes environment variables and self-defined variables.



10, thedeclarecommand is used to declare the variable type, similar totypeset,-arepresents an array.-irepresents an integer,-xsimilar toexport, specifying that the-rvariable is read-only.



11, a few special variables: for thePS1command prompt, for the use of thePS2escape character after the second line of the command prompt, the$pid of the shell,?



As the callback code for the last Run command, the callback code of 0 indicates that the command ran successfully.






12, thereadcommand can read the keyboard input to the variable, the-pparameters can specify the prompt information, such as:


$read"please input your name:"name


13,ulimitthe command can set the user's use of system resources restrictions.



14, the deletion of variable content can use,,,###%%%symbols, content substitution can be used/,//symbols.


 
$ {Variable # keyword} —— match from left to right, delete the shortest data. $ {Variable ## keywords}-matches from left to right. Delete the longest data.


$ {Variable% keyword}-matches from right to left. Delete the shortest data. $ {Variable %% keyword}-matches from right to left, deleting the longest data. $ {Variable / old string / new string}-matches from left to right, deleting the first matched data. $ {Variable // old string / new string}-matches from left to right, deleting all matching data.


15, variable value test and replacement can be used-,,,+=?



,:symbols, etc., effects such as the following:





Frequent use of key combinations--


Ctrl + C: Terminates the immediate command.
Ctrl + D: Enter end EOF to exit the current shell.
CTRL + M:enter key.




Ctrl + S: Pauses the output of the screen.
Ctrl + Q: Reply to the output of the screen.




Ctrl + U: Removes the entire line of commands under the prompt character.
Ctrl + Z: Pauses the immediate command.


Common wildcard characters and special symbols--
*: Random number of random characters.


?: Any one character. [abcd]: Any character in square brackets, that is, any one of a, b, c, and d [a-z]: Any character in the range from a to z. The key is the minus sign in the middle. Represents a range.

[^ abc]: ^ stands for reverse selection, that is, except abc. Feel free to one other character.

#: Gaze symbol. \: Escape character.

|: Pipeline. ;: Semicolon, a separator between several consecutive commands. ~: User home folder. $: Used to read variables.

&: Job control. Background job is currently commanded.

!: Logical NOT. /: Path separator. >, >>: Data stream redirection, output, respectively replacement and append. 2>, 2 >>: Data stream redirection, error output, no space between number 2 and angle brackets. <, <<: Data stream redirection. Enter.

' ':apostrophe. As mentioned above. Does not have variable substitution.

"": Double quotes with variable substitution function ``: Runnable commands between symbols, equivalent to $ (). (): Equivalent to a subshell. {}: Combination of command blocks.


Examples of how data flow redirection is used--


stdin,stdout,stderrin fact, is three special files, the file identifiers are 0, 1, 2, the following sample uses these numbers.
To copy the contents of a plain text file from the to file to, there are two ways to use data flow redirection:


fromtotofrom


Sometimes when a command is run, there are standard output, standard error output, and the standard output is redirected to a filefile:


$command > file


REDIRECT the standard error output to a filefile:


$command 2> file


To redirect the standard output, label error output at the same time to file files There are three ways to do this:


$command > file 2>&1$command 2> file >&2$command &> file


Notice how the numbers above are used.
/dev/nullis a special file that can be understood as an infinitely large spam site, capable of redirecting arbitrarily unwanted data to this file.



The command line runs several commands consecutively--



Method One: Use semicolons


$command1; command2


Method Two: Use&&and||symbols


$command1 && command2$command1 || command2


&&And that||is what is commonly referred to as short-circuit symbols.


Pipeline Command--


1. Pipeline



The pipeline is a vertical line|, the command on the left has standard output, and only the standard output is processed. Standard errors are ignored, the command on the right is acceptable for standard input, and several frequently used pipeline commands are described below.



2. Cut



In the ACT unit. Intercept part of the data.


$echo$PATH-d‘:‘-f1


In anPATHenvironment variable,-dspecify the delimiter as a colon, and the colon toPATHcut the contents of the environment variable.-fSpecifies the first field after the cut, which is the 1th field. You can also select multiple fields. separated by commas.-dthe specified delimiter can be a space, such as the following command:


$last|-d‘ ‘-f1$export|-c10-20


-cThe 10th to 20th characters of each line are intercepted.



3. grep



Matches the target string in the behavior unit. A successful match outputs an entire line of content, such as:


$topgrep init


Here are some of the frequently used parameters:


-c: Count the number of string matches. -i: Ignore uppercase and lowercase.


-n: output line number. -v: reverse selection, that is, output lines that do not match the string.


Grep can also be used in a separate format, such as the following:


<string><filename>


4. Sort



sortThat is, sort, such as:


$lssort -r


-rRepresents a reverse sort.



5, Uniq



uniqUsed to process repeated data, filtered only once, such as:


$last|-d‘ ‘-f1|-c


Displays the total number of times each account was logged in.






6. WC



wcHow many lines, strings, and characters are in the statistics text, such as:


$wc filename


The-lability to count rows and to-wcount strings.-cstatistical characters.



7. Tee



As you can see from the previous commands, the data flow is redirected to the file. There is no output on the screen. And thisteecan be bidirectional oriented. Side to file, side to screen, such as:


$ls | tee filename


lsThe results are redirected tofilenamethe same time also output to the screen.



8, TR



trUsed to delete or replace a string.


$ls|[a-z] [A-Z]


As in the example abovetr,lsReplace all lowercase letters in the results to capitalize.


$ls-d‘string‘


-dThe parameter specifies the string to delete.






9. Col



colFilter some of the data, options and parameters:


-x: Convert tab to equivalent space. -b: There are backslashes / hours in the file. Only the last character following the backslash is retained.


10. Join



Merge two rows of data into one line, such as the following:


$join [options] file1 file2


Options and parameters such as the following:


-t <string>: join separates data by space by default. -t specifies verbose separator. And find the string in file1 and file2, when the search is successful, the two rows of data of file1 and file2 are connected into one line, and the string is displayed only once. Show at the beginning of the line.


-i: Ignore uppercase and lowercase.

-1 <num>: The number 1, which specifies which field to analyze for the first document file1.

-2 <num>: The number 2. Specifies which field to use for the second document file2 for analysis.


11, paste



Merge multiple lines of text into a single line, with the defaultTabkey as the delimiter, and the syntax format for example:


$paste[options][files]


Often use the parameter to-dspecify the delimiter.



12, expand



expandTabconverts the key to a space.






13. Split



Separates large files into multiple small files. The syntax format is as follows:


$split[options][file]PREFIX


The frequently used option is-b. Specifies the small file size.-lSpecifies the number of small file rows.PREFIXprefix for small files. The ability to optionally specify a string that is defined for itself.



14, Xargs



xargsRead the standard input, separated by a space or line break, separate the standard input into multiple parameters, and then run the specified command, such as the following:


command


For example, the following command,/tmpunder the folder to findcorethe name of the file,


$find-name-type-print0|-0-f


..........



"Bash treasure Chest" Linux shell learning


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.