Three advanced variables and strings for the Linux shell

Source: Internet
Author: User
Tags arithmetic types of extensions

Advanced variable contains three parts
1. Variable expansion
2. Command replacement
3. Arithmetic Expansion

In the bash shell, the $ operator triggers the above three extensions in the following basic form:
Basic types of extensions examples
${variable name} variable extension ${filename}
$ (Command) command replacement $ (LS/)
$ (arithmetic)) Arithmetic extension $ ((5+3)
)

variable presence indicates a variable has value (contains null)
One, variable expansion: Test the existence and null value
basic usage of test variable "existence or not"
${the variable to be tested-default value}
if the variable being tested has a definition (including null), the default value of the variable to be measured is returned, if none is defined, then the default value is passed back.
A=yang a=
b=${a-' Hello '}
Echo $b
Because the variable a exists, the $b value is Yang, and if a exists, but is empty, then the $b value is empty. If a does not exist, $b for Hello
The variable is divided into two states, 1 exists (including NULL) 2 does not exist
${variables to be tested:-Default value}
if the variable being tested exists, it returns the default value of the variable to be measured, or returns the default value if it is not present or is empty.
A=yang a=
b=${a:-' Hello '}
Echo $b
Because the variable a exists, the $b value is Yang, and if a is empty or absent, the $b value is:-After the Hello
Summary:
If the variable extension criterion is only-then only the existence of the variable is judged.
Use:-To determine if the variable is empty except for the existence of the variable
A word: More than a ":", it is necessary to test both the existence and the null value of two cases.

[-N ${a:-}] && set-v
[] is the syntax of the test condition, the variable that is followed by the-N test is empty, is not empty, returns the True value (the length is not 0, the-Z length is 0 true).
${variables to be tested: = default}
if the variable being tested does not exist or is empty, the value to be measured is set to the default value after = =. If present, set the value of the variable to be measured.
A=yang
b=${a:= ' Hello '}
Echo $b
Because the variable a exists, the $b value is Yang, and if a is empty or absent, the $b value is: = after the Hello
b=${a:-' Hello ' and b=${a:= ' Hello '} appear to be the same, but:-When the variable A is empty or does not exist, the subsequent value Hello is the value of variable B, and a is still empty or does not exist. : = is when the variable a is empty or does not exist, the subsequent value Hello is the value of variable B, and defaults to the value of variable a (equivalent to assigning a value to a).
${variables to be tested:? Prompt message}
If the variable does not exist or is NULL, displays the variable name and the prompt message after the:, and immediately stops execution of the script.
Purpose: Ensure that the value of the variable must exist, otherwise the script is not executed.
#!/bin/bash
Fn=${1:? ' Error, provide the name of the directory you want to delete '} to check the first parameter passed in, if it is not empty, display the prompt message, and stop the script.
Echo ' The directory command you want to delete is: '
echo "Rm-rf ~/$FN"
testing the "existence" of variables
{variables to be tested: + truth}
if the variable exists and is not empty, it returns the "true value", otherwise the go home is passed.
A=123
B=${a:+ ' true '}
Echo $b
Because a exists and the value is not NULL, $b is true if a does not exist or a is empty, then the $b value is empty.
Summary:
: Empty test null value
-Negative measurement does not exist
= set value to NULL value variable set a default value
? If you have any questions, check the conditions.
+ Forward test present

two, Variable extension: Take string slice, string length
the first character of the string, numbered 0, and the character number of the right neighbor, is incremented by 1. Next, describe how a part of a string and how to get the string length
take a string slice
${variable: Position start} Position starting point is equivalent to the number below.
A= "Hello,world"
B=${a:3}
Echo $b
Starts with the 4th character, to the end. $b value is Lo,world
${variable: Position start: Length}
A= "Hello,world"
B=${a:3:5}
Echo $b
Starts with a 4th character, a total of 5 characters. The value of the $b is Lo,wo
take partial position parameter
${@:n} n is a positive integer, which is the position starting point to the last
!/bin/bash
Echo
Echo ${@:2} In addition to the command itself, from the 2nd character (the command itself is 0, numbered 3) to the last
./script.sh 12 23 34 45 The return value is 23 34 45
${@:n:m} N, M is a positive integer, n is the starting character, M is the length
!/bin/bash
Echo
Echo ${@:2:4} length is 4
./script.sh 12 23 34 45 56 67 78 The return value is 23 34 45 56
Calculating string Lengths
${#变量名称} returns the string length of a variable value
[email protected] ~]# cat 1.sh
#!/bin/bash
#
A= '/etc/passwd '
echo ${#A}
[Email protected] ~]# bash 1.sh
11
[Email protected] ~]#
${#数组 [@]} to get the number of array elements
${#数组 [*]} to get the number of array elements

third, variable expansion: Contrast style
In this case, the "contrast style" is intended to intercept a portion of a variable's value (a string). The practice is to remove or replace partial strings that conform to the style.
by the front of the string, delete the matching person
from the front (leftmost), compare the value of the variable to remove the shortest matched string.
${variable # style}
A= "/usr/sbin/ntpdate"
b=${a#/*/}
Echo $b
/*/represents, where a pair/between a string, compared to match, that $b value is sbin/ntpdate
from the front (leftmost), compare the value of the variable to remove the best-fit string.
${variable # #样式}
A= "/usr/sbin/ntpdate"
b=${a##/*/}
Echo $b
/*/represents, where a pair/between a string, compared to match, that $b value is ntpdate
by comparing the strings, delete the matching person
From the back (right-most), compare the value of the variable to remove the shortest matched string.
${variable% style}

A= "/usr/sbin/ntpdate"
b=${a%/*}
Echo $b
/* represents, where a pair/between a string, compared to match, that $b value of/usr/sbin
From the back (right-most), compare the value of the variable to remove the best-fit string.
${variable% style}

A= "/usr/sbin/ntpdate" a= "www.baidu.com"
b=${a%%/*} b=${a%%.*}
echo $b Echo $b at this time $b for www
/* represents, where a pair/between a string, the contrast matches, the $b value is empty
Summary:
Grammatical uses
${variable # Style} by the front of the comparison, the deletion of the shortest
The ${variable # #样式} is contrasted by the front and the longest deleted
${variable% style} by the back of the comparison, delete the shortest
${variable percent style} by the back of the comparison, the longest delete

Replace or delete a partial string
Replaces only the string of the first contrasting symbol (if deleted, the replacement word prompt is empty)
${variable/style/replacement string}

A= "Root:x:0:0:root:/root:/bin/bash"
b=${a/:/,}
Echo $b
$b value is Root,x:0:0:root:/root:/bin/bash
Replace all matched strings (if deleted, the replacement word prompt is empty)
${variable//style/replacement string}

A= "Root:x:0:0:root:/root:/bin/bash"
b=${a//:/,}
Echo $b
$b value is Root,x,0,0,root,/root,/bin/bash
b=${a/#s/} Delete lines beginning with s with a space ending
b=${a/%s/} Delete lines ending in S
four, variable extension: Take the variable name list, array index list
take a list of variable names
${! start string @} or ${! start String *}
echo ${[email protected]} or ${!x*} variable name beginning with X.

a1=11
A2=dfds
B=sfs
echo ${[email protected]} value is A1, A2
take an array index list
${! array variable [@]} or ${! array variable [*]}
[email protected] ~]# cat 1.sh
#!/bin/bash
#
A= (one three four five)
For i in "${!a[@]}"
Do
echo "$i string is ${a[$i]}"
Done
[Email protected] ~]# bash 1.sh
The No. 0 string is one
The 1th string is two
A 2nd string is three
The 3rd string is four
A 4th string is five
[Email protected] ~]#
v. Command substitution
The command substitution here refers to putting the standard output of the command execution into a variable, in two ways:
modern notation: variable name =$ (command)
Legacy notation: variable name = ' Command '

The old-fashioned quotation marks are inverted, usually above the TAB key.
[Email protected] ~]# ls/home/
Lost+found Nagios Xguest
[email protected] ~]# cat 1.sh
#!/bin/bash
#
a=$ (Ls/home)
For f in $a
Do
Echo $f
Done
[Email protected] ~]# bash 1.sh
Lost+found
Nagios
Xguest
[Email protected] ~]#
IFS is the specified delimiter, default is blank or tab
Vi. Arithmetic Expansion
If the a=8+4 b= $a echo $b The output is definitely 8+4 because the bash shell treats any value stored in the variable as a character string.
Syntax for arithmetic extension: $ (arithmetic)
A=3+4
b= $a
Echo $b
The output is 7
Seven, single quotation marks, double quotation marks, the difference of anti-quotation marks
Single-Quote string restrictions:
1, any character in single quotation marks will be output as is, the variable in the single quote string is invalid;
2. Single quotation marks cannot appear in single quote strings (not after using escape characters for single quotes).

Advantages of double quotes :
1, double quotes can have variables
2. Escape characters can appear in double quotes

Anti-Quote
The inverted quote is an execution command .
Date is a command that can view dates
The PWD is an internal variable, and the Echo $PWD displays the current path
Let's take a look at the effects of using different symbols.
1, dollar sign $ in single, double quotes, the $ in single quotation marks will retain its literal meaning, a variable reference will occur in double quotes
[Email protected] ~]# echo ' $PWD '
$PWD
[Email protected] ~]# echo "$PWD"
/root
2, anti-slash \ In single, double quotes in the performance, single quotation mark \ will retain its literal meaning, double quotes in the \ escape character behind (loss of special meaning)
[[email protected] ~]# echo ' \ $PWD '
\ $PWD
[[email protected] ~]# echo "\ $PWD"
$PWD
3, the anti-quotation marks and other two different symbols, the string surrounded by anti-quotes will be run, take its results.
[[email protected] ~]# echo ' Date '
Date
[[email protected] ~]# echo "Date"
Date
[[email protected] ~]# echo ' Date '
Fri May 1 12:39:21 CST 2015
Note: Date in the anti-quotation marks is executed as a command, which contains exactly the commands from the output information.
Summary:
Use single quotation marks when a string is required;
Use double quotation marks when internal variables are included;
Pawn shop to catch command output, with anti-quote;


This article is from the "Welcome to Linux World" blog, so be sure to keep this source http://linuxnote.blog.51cto.com/9876511/1641172

Three advanced variables and strings for the Linux shell

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.