some shell variables

(1) The usage part of ${}, ## and %% in the shell

 Suppose we define a variable as:
file=/dir1/dir2/dir3/my.file.txt

You can replace them with ${ } to get different values:
${file#*/}: delete the first / and its left string: dir1/dir2/dir3/my.file.txt
${file##* /}: delete the last / and the string to the left: my.file.txt
${file#*.}: delete the first . and the string to the left: file.txt
${file##* .}: delete the last . and the string to the left: txt
${file%/*}: delete the last / and the string to the right: /dir1/dir2/dir3
${file%%/*} : delete the first / and the string to the right: (null)
${file%.*}: delete the last . and the string to the right: /dir1/dir2/dir3/my.file
${ file%%.*}: delete the first . and the string to the right: /dir1/dir2/dir3/my

The way to remember is:
# is to remove the left (# on the keyboard is on the left of $)
% is to remove the right (% is on the right of $ on the keyboard) A
single symbol is the smallest match; two symbols are the largest match
${file:0:5 }: Extract the leftmost 5 bytes: /dir1
${file:5:5}: Extract the 5 consecutive bytes to the right of the 5th byte: /dir2

You can also replace strings in variable values:
${file/dir/path}: replace the first dir with path: /path1/dir2/dir3/my.file.txt
${file//dir/path }: replace all dir with path: /path1/path2/path3/my.file.txt

Using ${ } can also assign values ​​to different variable states (unset, null, non-null):
${file-my.file.txt} : If $file is not set, use my.file.txt as the return value. (null and non-null values ​​are not processed)
${file:-my.file.txt} : If $file is not set or is null, use my.file.txt as the return value. (No processing if non-null)
${file+my.file.txt} : If $file is set to null or non-null, use my.file.txt as the return value. (No processing if not set)
${file:+my.file.txt} : If $file is non-null, use my.file.txt as the return value. (No processing if not set and empty)
${file=my.file.txt} : If $file is not set, use my.file.txt as the return value, and assign $file to my.file.txt . (null and non-null values ​​are not processed)
${file:=my.file.txt} : If $file is not set or is null, use my.file.txt as the return value, and assign $file for my.file.txt. (No processing if non-null)
${file?my.file.txt} : If $file is not set, output my.file.txt to STDERR. (null and non-null values ​​are not processed)


${file:?my.file.txt} : If $file is not set or is empty, output my.file.txt to STDERR. (Not processed when it is not empty)

${#var} calculates the length of a variable value:


${#file} gives 27 because /dir1/dir2/dir3/my.file.txt is 27 bytes

Reprinted from: http://blog.csdn.net/shmilyringpull/article/details/7631106

 

 

(2) Special usage of $0, $?, $!, etc.

 Variable description:
$$
Shell's own PID (ProcessID)
$!
The PID of the background process that Shell runs last
$?
The end code (return value) of the last running command
$
-List of Flags set by the Set command
$* List of
all parameters . For example, when "$*" is enclosed in """, all parameters are output in the form of "$1 $2 ... $n".
$@
A list of all parameters. For example, when "$@" is enclosed in """, all parameters are output in the form of "$1" "$2" … "$n".
$#
The number of parameters added to the shell
$0
The file name of the shell itself
$1~$n
are added to each parameter value of the shell. $1 is the first parameter, $2 is the second parameter... .
Let's write a simple script first, and then explain the meaning of each variable after execution
# touch variable
# vi variable The
script content is as follows:
#!/bin/sh
echo "number:$#"
echo "scname:$0"
echo "first :$1 "
echo "second:$2"
echo "argume:



Execute the script
# ./variable aa bb
number:2
scname:./variable
first: aa
second:bb
argume:aa bb
You can see by displaying the result:
$# is the number of arguments passed to the script
$0 is the name of the script itself
$1 is the first parameter
passed to the shell script $2 is the second parameter passed to the shell script
$@ is a list of all parameters passed to the script

 Reprinted from: http://blog.sina.com.cn/s/blog_464f6dba0100psy9.html

 (3) Bracket part

One, parentheses, parentheses ()
  1, single parentheses ()
    ① command group. Commands in parentheses will be executed sequentially in a new subshell, so variables in parentheses cannot be used by the rest of the script. Multiple commands in parentheses are separated by semicolons. The last command can be without a semicolon, and there is no need to have spaces between each command and the parentheses.
    ②Command substitution. Equivalent to `cmd`, the shell scans the command line once, finds the $(cmd) structure, executes the cmd in $(cmd) once, gets its standard output, and puts this output into the original command. Some shells do not support it, such as tcsh.
    ③ used to initialize the array. Such as: array=(abcd)
  2. Double parentheses (( ))
    ①Integer expansion. This extended calculation is an integer calculation and does not support floating point. The ((exp)) construct expands and evaluates an arithmetic expression, returning an exit status code of 1 if the expression evaluates to 0, or "false", and a non-zero value returned by an expression The exit status code will be 0, or "true". If it is a logical judgment, the expression exp is 1 if it is true, and 0 if it is false.
    ②As long as the operators and expressions in parentheses conform to the C language operation rules, they can be used in $((exp)), even ternary operators. When performing operations with different carry (such as binary, octal, and hexadecimal), the output results are all automatically converted into decimal. For example: echo $((16#5f)) The result is 95 (hexadecimal to decimal)
    ③ Simply use (( )) to redefine the variable value, such as a=5; ((a++)) to redefine $a For 6
    ④ variables in double brackets can not use the $ sign prefix. Multiple expressions within parentheses are supported separated by commas.
[python] view plaincopy
if ($i<5) 
if [ $i -lt 5 ] 
if [ $a -ne 1 -a $a != 2 ] 
if [ $a -ne 1] && [ $a != 2 ] 
if [[ $a != 1 && $a != 2 ]] 
  
for i in $(seq 0 4);do echo $i;done 
for i in `seq 0 4`;do echo $i;done 
for ((i=0;i<5;i++));do echo $i;done 
for i in {0..4};do echo $i;done 
2) Square brackets, square brackets []
  1. Single brackets []
    ①The internal commands of bash, [ and test are equivalent. If we don't specify the absolute path, we usually use the commands that come with bash. The left square bracket in the if/test structure is the command identifier for calling test, and the right square bracket is used to close the conditional judgment. This command takes its argument as a comparison expression or as a file test, and returns an exit status code based on the result of the comparison. The closing bracket is not required in the if/test structure, but it is required in the new version of Bash.
    ②The only comparison operators available in Test and [] are == and !=, both of which are used for string comparison, but not for integer comparison. Integer comparison can only use the form of -eq, -gt. Neither string comparisons nor integer comparisons support the greater-than sign and the less-than sign. If you really want to use it, you can use the escaped form for string comparison. If you compare "ab" and "bc": [ ab \< bc ], the result is true, that is, the return status is 0. Logical AND and logical OR in [ ] are expressed using -a and -o.
    ③ character range. Used as part of a regular expression to describe a range of characters to match. Regular expressions cannot be used within square brackets for test purposes.
    ④ In the context of an array structure, square brackets are used to refer to the number of each element in the array.
  2. Double square brackets [[ ]]
    ①[[ is a keyword in the bash programming language. Not a command, the [[ ]] construct is more general than the [ ] construct. All characters between [[ and ]] do not have filename expansion or word splitting, but parameter expansion and command substitution will occur.
    ② Supports pattern matching of strings, and even supports regular expressions of the shell when using the =~ operator. String comparisons can use the right-hand side as a pattern, not just a string, such as [[ hello == hell? ]], which results in true. [[ ]] matches strings or wildcards without quotes.
    ③Using the [[...]] conditional judgment structure instead of [...] can prevent many logical errors in the script. For example, the &&, ||, < and > operators can normally exist in the [[ ]] conditional judgment structure, but if they appear in the [ ] structure, an error will be reported.
    ④bash treats the expression in double square brackets as a single element and returns an exit status code.
3) Braces, curly brackets {}
  1. Conventional usage.
    ①Brace expansion. (globbing) will expand the filename in curly braces. Within curly braces, whitespace is not allowed unless the whitespace is quoted or escaped. The first: expands the comma-separated list of files in curly braces. For example, touch {a,b}.txt results in a.txt b.txt. The second: expands the sequential file list separated by dots (..) in curly brackets, such as: touch {a..d}.txt The result is a.txt b.txt c.txt d.txt
[python ] view plaincopy
bogon:/home/bash # ls {ex1,ex2}.sh 
ex1.sh ex2.sh 
bogon:/home/bash # ls {ex{1..3},ex4}.sh 
ex1.sh ex2.sh ex3.sh ex4.sh 
bogon:/home/bash # ls {ex[ 1-3], ex4}.sh 
ex1.sh ex2.sh ex3.sh ex4.sh 
    ② The code block, also known as the inner group, actually creates an anonymous function. Unlike commands in parentheses, commands in curly brackets do not open a new subshell to run, that is, the rest of the script can still use the variables in the brackets. The commands in parentheses are separated by semicolons, and the last one must also have a semicolon. There must be a space between the first command of {} and the opening parenthesis.
   2) Several special substitution structures: ${var:-string}, ${var:+string}, ${var:=string}, ${var:?string}
      A, ${var:-string} and ${var:=string}: If the variable var is empty, use string to replace ${var:-string} on the command line, otherwise when the variable var is not empty, replace ${ with the value of the variable var var:-string}; The replacement rule for ${var:=string} is the same as ${var:-string}, the difference is that if var is empty, ${var:=string} is replaced with string At the same time as ${var:=string}, assign string to variable var: A very common usage of ${var:=string} is to judge whether a variable is assigned a value, and if not, assign a default value to it.
      B. The replacement rule of ${var:+string} is the opposite of the above, that is, only when var is not empty, it will be replaced with string. If var is empty, it will not be replaced or replaced with the value of variable var, that is, empty value. (Because the variable var is empty at this time, these two statements are equivalent)
      C, ${var:?string} The replacement rule is: if the variable var is not empty, replace ${var with the value of the variable var :?string}; if the variable var is empty, output string to standard error and exit from the script. We can use this feature to check if the value of a variable is set.
      Supplementary expansion: In the above five replacement structures, string is not necessarily constant, but the value of another variable or the output of a command can be used.
  3) Four pattern matching replacement structures: ${var%pattern}, ${var%%pattern}, ${var#pattern}, ${var##pattern}
     The first pattern: ${variable%pattern}, In this pattern, the shell looks in the variable to see if it ends with a given pattern pattern. If so, remove the contents of the variable from the command line with the shortest matching pattern on the right.
     The second pattern: ${variable%%pattern }, in this mode, the shell looks in the variable to see if it ends with the given pattern pattern, if so, remove the content of the variable from the command line and remove the longest matching pattern on the right. The
     third pattern: ${variable #pattern} In this pattern, the shell looks in the variable to see if it starts with the given pattern pattern. If so, remove the shortest matching pattern on the left from the contents of the variable from the command line.
     The fourth pattern: ${variable##pattern} In this pattern, the shell looks in the variable to see if it ends with the given pattern pattern. If so, remove the longest right of the contents of the variable from the command line. Matching patterns
     None of the four patterns will change the value of the variable. Among them, only when the * matching symbol is used in the pattern, there is a difference between % and %%, # and ##. The pattern in the structure supports wildcards, * means zero or more arbitrary characters, ? means zero or one arbitrary character, [...] means matching the characters inside the brackets, [!...] means not matching the brackets Characters inside
[python] view plaincopy
bogon:/home/bash # var=testcase 
bogon:/home/bash # echo $var 
testcase 
bogon:/home/bash # echo ${var%s*e} 
testca 
bogon:/home /bash # echo $var 
testcase 
bogon:/home/bash # echo ${var%%s*e} 
te 
bogon:/home/bash # echo ${var#?e} 
stcase 
bogon:/home/bash # echo $ {var##?e} 
stcase 
bogon:/home/bash # echo ${var##*e} 
 
bogon:/home/bash # echo ${var##*s} 

bogon:/home/bash # echo ${var##test} 
case 

 

http://blog.csdn.net/tttyd/article/details/11742241

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326446043&siteId=291194637