Shell script Programming Tips--for linux,bash and other technical summaries

Source: Internet
Author: User
Tags add numbers aliases case statement

I've seen a few books on Shell programming and Linux commands, and this one is particularly impressive, though it's still an introductory book, but I think it's a little bit more detailed and broader than I've ever seen before. Today just read, but also today began to decide to open a blog, the content of this book in the technical summary, as my first technical blog good.


Starting the interactive shell will first read/etc/profile ~/.profile ~/.BASHRC/ETC/BASHRC

The less option-X prevents the screen from refreshing, and the content displayed in the previous terminal will not be lost, as if it were the default mode of the console.


Alias alias with Unalias can be canceled, aliases in the need to repeatedly type complex values when the most useful, there is RM and other dangerous operations to join the-I option to prevent the misuse of instructions before adding \ can not use aliases


History first the current shell command is only stored in memory before exiting the login, and is called with the history command, not inside the. bash_history file

Histsize defines the maximum number of stored commands,

Hisfilesize defines the maximum history file size,

The Histcontrol definition ignores leading spaces,

Histingore defines a command that does not need to be stored, where ignoredups ignores duplicate rows, Ignorespace ignores lines with leading spaces, Ignoreboth ignores both

Histfile Defining History files


Shell all parameters $* [email protected] the latter is separate, remember to use double quotation marks, otherwise read into the parameters are still separated by a space to pass to the variable; $ #为参数的总个数

About calling functions in the shell, there are two ways to pass the return value of a function.

1 Pass exit return so that you use $ immediately after the call? This value can get the outgoing value

2 Assign the result of all echo generated by a=function to a, and $? can get success function or not, 0 success 1 failure


The shopt command is used to manage bash's various options supervisor Bashopots

The set command is used to manage shellopts primarily for bash and this is for the shell environment set with the '-' sign on function ' + ' Cancel function


Where Pipefail is turned on when using the pipe command, the exit code returns a non-0 after any stage of the pipeline fails

It is also possible to use the Pipestatus array to record all the values of an array at once, otherwise the value will be overwritten by the result of any subsequent command, starting at the far right of the pipe 0


Bash_command displays the currently running command, which is useful when interrupted


There are 4 useful array variables I remember, funcname is used to display the name of a function that is currently running, from 0 onwards to the caller

Bash_source displays the name of the script that is running, and also the

Lineno the number of rows displayed in the current script

Bash_lineno[i] represents the line number used in the source file to invoke Funcname[i] so that the number of rows in the caller can be represented as long as bash_lineno[0] is used in the callee.

Bash_version used to record bash version names

PWD for pwd command results and OLDPWD for previous directory available ' CD-' command return


TimeFormat is used to control the output of the time command format, can be used to detect the process run time time-p commmand, divided into the total duration, the user space system space time


Ppid is the PID of the caller and $$ shows the PID of the current process

Random numbers from 0 to 32767,

Seconds will add one per second default is the current time of the shell login

Replay is the default input, which is typically the last input

bash_xtraced This variable will output the Set-x output to the file descriptor specified by the variable when set-x is set? Must be a file descriptor for the experiment?


The Globignore variable is used to let the * wildcard ignore the result of some matching pattern, separated by a colon

IFS is a bash user-delimited input character spaces tab and line break

Tmout and read-t are also used for timeout settings and timeout commands.


Shell matches with * Match 0 to infinity? Match one must, and {} curly braces can be placed into all optional items, separated by commas

Turn on Shopt-s dotglob to match the file at the beginning of the point. and.. except

Nullglob can not match wildcard characters to match items when they are not matched

Extglob can extend the match like? (models) matches any one + () match one or more * () matches 0 to more

@ () match one! () match except for one


Several available classes remember here [A-z] equals [[: Alpha::] [[: Alnum:]] [[: Blank:]] Space tab [[: Cntrl:]] non-printing control character [[:d ight:]] [[: Graph:]] alphanumeric punctuation [[: L Ower:]] [[: Upper:]] [[:p rint:]] printable character [[:p UNCT:]] [[: Space:]] blank character [[: Xdigit:]]


all the characters in a single quotation mark in the shell nonalphanumeric not be interpreted in double quotes other than the $ reference variable will not be interpreted

Special character such as semicolon exclamation mark (History command) & symbol Various parentheses can be escaped with backslash


Test is the same as the [] command effect, where the [] is [the parameter does not also matter if there is-o-g whether it belongs to the current user and group-U has been modified since the last visit


use [[args =~ Regular expression]] to bring into the regular expression with the right side of the match to the left of the form can be (. +) (. *) ([email protected]) and so on 1 or more 0 to more than 1 characters match after the use of Bash_rematch Array can take out each matching item


Case statement A total of 3 kinds of sentence way;; This is the most common, is the C language switch in the meaning of break.

;; & This means it's going to go down to match work.

;& This means that the next item is also used as a match, and then the end


The loop can finally be used to enter the desired content from the file with the < symbol

For loop has for a in B and for ((;;)) This C-language approach to both of these

Continue and break followed by a number can be specified to jump out of a few loops is convenient

Select a in B, the auto-generate menu takes advantage of the PS3 variable as a prompt, the user enters the number as the reply variable, and A is the input number that corresponds to the project name select generated menu can only be exited with an interrupt method he is an infinite loop.


The numeric operation of a variable but with the Let Command Expr Command and (()) parentheses for the third of the values to be obtained, you need to add $ to the front, the advantage is that the internal calculation does not have to add the $ symbol inside the variable

Variable length is the value of ${#para}


Cropping variables: ${para:pos:num} variables begin with the POS position (counting from 0) before Num characters are cropped and displayed, where the NUM field and the preceding colon can be omitted if you want to calculate the cropping position from the end:-pos Remember that there is a space between the symbol and the colon

There is also a pattern matching crop using {para#mod} {para# #mod} {para%mod} {Para%%mod} Two symbols are greedy matches always match the longest segment, one symbol matches the shortest paragraph, #是从开头% is from the end, the MoD area uses Bash's Match and pass mode

{Para^character} symbol can be changed to ^ ^,, a total of 4 different means to change the corresponding letter in the para to uppercase or lowercase, the two characters are all changed to a single word only match the first character of the variable, regardless of match mismatch.


Variable lookup substitution ${var//a/b} replace a in Var with a B, the double slash means replace all, and if replaced by a single slash, replace only the first one if the character you want to replace begins with a # character instead of the ^ character, and the% indicates the end of the wildcard character, if you want to delete it./b Part of the omission on the line


Provide a default value of ${a:-b} If a does not exist or is empty then use B {a:=b} with the previous single A will be assigned a value B

[A?b] has a value even if empty is also a otherwise b [a+b] has a value of B no value for a

$[!var] is 2 times the value is referenced by the $var before its value is referenced


Getopts can handle simple command-line arguments, separating the parameter options into the format getopts optstring name where the options are specified in optstring and whether to add a colon after the argument, name holds the current option, Optarg holds the parameters for the current option, OP The index in the Tind where the next option to be queried starts at 1


Arrays can be assigned in a single pass can be sparse assignment (not sequential assignment by ordinal), with the value can be added a= (${a[@] B} or Apply ${#a [@]} to indicate the total number of elements of the array or reduce the use of unset directly unset the array name is to cancel the entire array,

The input of the array assignment is not necessarily a space for this as long as the IFS can be modified to pay attention to save the first or you can put IFS modification and instruction run on the same line so that IFS modification validity is only this line.

If you use IFS and read-a to read into an array, the input of the same line is divided into multiple copies of the delimiter and placed in each item of the array.

You can also crop the total elements of an array by using the variable clipping method


An associative array can use a string as an array index and can reverse-find for B-in ${!a[@]}, at which point the value of B is indexed when the value a[b] gets the corresponding result in the array

You can add another array to an array to take advantage of a+= ("${b[@]}")


Nohup for the backend to run the terminal shut down also no harm

Wait can select the process to wait for the end (must be a child of the current process or return directly)


Interactive login Shell/etc/profile ~/.profile ~/.BASHRC/ETC/BASHRC

Interactive non-logon shell reads into ~/.BASHRC/ETC/BASHRC when typing shell in shell

Non-interactive shell is commonly used in scripts to read bash_env variables without reading


Use the history command! You can bring up the used commands, add numbers or the first few letters of the command.


You can use the Stat command to obtain specific information about a file's permissions to simulate the LS command more useful

The cat command can mark line numbers, non-blank lines leave a single blank line, display nonprinting characters-V, and so on

The maktemp command can be used to create a zero file name, and you can use X to specify the number of randomly generated letters


REDIRECT << symbol after using <<-words, each line of text entered after all ignores leading spaces, which helps to clear the level of the Code


When you combine two files with a join, you can choose to display everything by field combination, etc.


-T in the Cut command if you specify a space, you can only recognize a single space if the number of spaces inside each line is different, it causes the domain selection error


The Shuf instruction is used to randomly arrange the specified sequence, either directly in the parameter, using-e or the specified file, each line in the file to write a random character, or you can use the-I to 1-6 such a form


Paste also put two files together by default will all paste up, not the same part also regardless, is simply the corresponding line number of the same line affixed together, you can specify the delimiter with-D, you can specify multiple, placed in a different two columns


PR can be printed according to the specified number of lines per line, using-t to remove the form header


printf directives specify format strings as C language


The TR command uses [] to include characters that need to be matched, or to use [: Alpha:] and so on.


Uniq command-w-s can specify output or ignore the first n characters, use-u-d to specify output distinct rows or duplicate rows using-F to specify the comparison to ignore the previous fields, fields separated by a space tab


The factor command is used to output the prime number of specified numbers


ID groups getent where the third one is used to get the specified information in the specified database

Md5sum is used to calculate the checksum value, if you add-c to calculate the value and the emitted good text can be used to verify the checksum value, of course, placed under the same directory


The MKFIFO is used to make pipeline files, but the pipe must be open in either direction or it will not work properly.


SEQ is used to output a sequence that can be specified with the B in seq a b C


Timeout is used to create a time limit, timeout-s signal specifies that a signal signal is sent to the program


The xargs is used to pass parameters to the specified command, optionally passing a few

Yes is used to repeat the output of a constant value in a place that needs constant answers.


For the moment summed up so much more chaos is to give yourself a review of the reference to continue to consolidate and improve









Shell script Programming Tips--for linux,bash and other technical summaries

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.