Shell Programming (iv): variables

Source: Internet
Author: User
Tags array length lowercase posix uppercase letter variable scope

Variable

Variables are abstract concepts that can store calculated results or can represent values. Variables can be accessed by variable names.

Variable declaration

Declaring variables is generally used in the following way:

[email protected]:~# var=test #这里声明了一个名为 var 的变量,并给他赋值为test[email protected]:~# # “=”前后不能有空格,变量名区分大小写

Or the following way:

[email protected]:~/HtmlDOM/Libs# declare var1=123[email protected]:~/HtmlDOM/Libs# export var2=234[email protected]:~/HtmlDOM/Libs# [email protected]:~/HtmlDOM/Libs# env var3=333

The command used above: Declare,export,env can declare variables, except that variable scopes are different.
There are two types of variables in the shell:

    • Shell Local Variables
      Local variables are defined in a script or command, only valid in the current shell instance, and other shell-initiated programs cannot access local variables.
      The variables defined by the assignment statement can be defined by the following methods
      [Email protected]:~/htmldom/libs# declare var1=123
      [Email protected]:~/htmldom/libs# var1=123

    • User Environment variables
      All programs, including shell-initiated programs, can access environment variables, and some programs require environment variables to keep them running properly. Shell scripts can also define environment variables when necessary.
      The shell private variables exported through the export syntax can be exported using the following method to export the user environment variables
      Export x =2
      Declare-x x=2
Variables used to display shell variables
    • Env This is a tool, or a Linux command, that displays the user's environment variables.
    • Set displays the user's local variables and user environment variables.
    • Export Displays the shell local variables that are exported as user variables, and displays the variables ' properties, that is, the variables that are exported to the environment variables by local variables (such as exporting WWC an environment variable or exporting an environment variable through declare-x LCY)
    • Declare displays the user's shell variables (local variables and environment variables) as set
DECLARE command:
    # 语法:declare [-aAfFgilnrtux] [-p] [name[=value] ...]    # 描述: declare 用来声明变量和配置变量的属性,如果declare后面没有参数,将会显示全部变量的属性和值。    # 参数                -f   限制行动或显示函数名称和定义                -F  只限制显示函数名(加上行号和源文件时调试)                -g  在shell函数中使用时创建全局变量;否则忽略                -p  显示每个变量的属性和值。    # 属性设置参数                -a  声明一个索引数组                -A  声明一个聚合数组                -i   变量值为整数,当给变量赋值为非整数值时变量为0                -l   给变量赋值时转换成小写字母                -n  将名称引用为其值命名的变量。                -r   只读变量                -t  使名称具有“trace”属性                -u  给变量赋值时转换成大写字母                -x  导出变量到用户环境变量
Export command
    # 语法: export [-fn] [name[=value] ...] or export -p    # 描述:从shell变量导出属性,将自动导出的每个名称标记为随后执行的命令的环境。如果提供了值,则在导出之前分配值。    # 参数     -f     引用shell函数     -n     从每个变量删除导出属性     -p     显示已导出的函数和变量清单
Set command
    # syntax: set [-ABEFHKMNPTUVXBCHP] [-O option-name] [--] [arg ...] # Description: Sets or cancels the value of the shell parameter and the positional parameter.    Change the value of the shell and positional parameters, or display the name and value of the shell variable.      # parameter:-A variable that is marked for export and modified or created.      -B immediately notifies the terminating task.      -e If a command with a non-0 status exits, exit immediately.      -F Disables File name generation (global).      -H Remember the location of the command to find.      -K All assignment parameters are placed in the context of a command, not just the command in front of the command name.      -M turn on task control.      -N reads commands, but does not execute them.        -O option-name sets the variable corresponding to the option name: Allexport same as-a braceexpand and-b Emacs              Use the Emacs-style line editing interface.              Errexit and-e same errtrace and-e same functrace and-t same hashall and-h same Histexpand is the same as-H history open command historical ignoreeof when reading EOF, the shell does not exit Interacti Ve-comments allow annotations to appear in the interactive command line keyword same AS-K monitor same a              S-m noclobber same as-c noexec same as-n noglob same as-f  Nolog      Currently accepted but ignored notify same as-b Nounset same as-u onecmd same as              The return value of the-t physical same as-p Pipefail pipeline is the last state of a command that exits in a non-0 state, or zero if no command with a non-0 state exits.              POSIX changes the behavior of bash, and the default action differs from the POSIX standard to match the criteria.       Privileged same as-p verbose same as-v VI using the VI-style line editing interface Xtrace Same As-x-P opens when a true valid user ID does not match. Cancels the processing of the $env file and imports the Shell function.      Turning this option off will result in a valid UID and GID set to true UID and GID.      -T exits after reading and executing a command.      -U treats a variable that is not set as an error when it is replaced.      -V Prints the input line of the shell.      -X Prints the command and its execution parameters.      -B Shell will execute support extension-c if set, the redirection output is not allowed to overwrite existing regular files.      -E If set, the Err capture is inherited by the shell function. -H Enable! Style history replacement.      This flag is the default when the shell is interactive.      -P If set, do not parse symbolic links when executing commands such as changing the current directory's CD. -T if set, debug capture inherits from the Shell function--assigns the remaining parameters to the positional parameters.      If there are no parameters left, then the positional parameters are not set. -Assigns the remaining parameters to the positional parameters. The-X and-v options are turned off.
ENV command
    # 描述: 在修改的环境中运行程序,将每个名称设置为环境中的值并运行命令。对长参数的强制参数也必须是短参数。    # 语法: env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]    # 参数        -i, --ignore-environment              从一个空的环境开始。        -0, --null              用NUL,而不是newline结束每个输出行。        -u, --unset=NAME              从环境中删除变量。    # 如果没有参数则打印当前环境中的变量
Variable Scope Shell variable

The shell variable is equivalent to a global variable that can be used in a child shell, function. If you declare a variable directly in a function or use DECLARE-G to declare a variable, this variable is a global variable.

Such as:

# variable=value# declare variable=value
function variables

You can declare a function (local) variable using the local command, which can only be accessed within a function, which is a shell (global) variable if the local command is not applicable.

function test(){    variable=123; # 全局变量    declare -g v=2 # 全局变量    local a=123 # 函数(局部)变量,只能在函数内访问}
Variable cancellation

Use a unset command to delete a variable

unset command
    # 语法: unset [-f] [-v] [-n] [name ...]    # 描述: 撤销shell变量和函数的值和属性。对于每个名称,删除相应的变量或函数。    # 参数:        -f  将name参数视为函数        -v  将name参数视为变量        -n  每个名称视为一个名称引用,并将变量本身设置为unset。而不是它引用的变量。        # 没有选项,unset首先尝试取消设置一个变量,如果失败,则尝试取消设置一个函数。        # 注意:只读变量不能被unset        [email protected]:~# declare -r NAME=raojl        [email protected]:~# unset NAME        -bash: unset: NAME: cannot unset: readonly variable        
Variable invocation

Variable names are subject to the following rules when declaring variables with one variable:

    1. Cannot start with special characters (except _), numbers, dollar symbols ($)
    2. Variable name cannot be a pure number
    3. Variable names can be combinations of English or numeric or special characters (_)

The variable is called in $var the form before the variable, such as:

[email protected]:~# name=raojl # 声明一个名为name的变量并赋值为raojl[email protected]:~# echo $name # 调用变量nameraojl  

Variable names can be used within double quotation marks, "" and the shell interprets the variables within the quotation marks, ‘‘ without interpreting the variables. Such as:

You can also ${variable} wrap variables in the form of curly braces, which you can use in order to avoid the variable names being interfered by other characters, such as:

$符号Parameter extensions, command substitutions, or arithmetic extensions are introduced. The parameter name or symbol to be extended can be enclosed in parentheses, which is optional, but you can protect the variable from being extended in a character that can be interpreted as part of the name.

Parameter extension
       The value of the ${parameter} parameter is replaced. Parentheses are required when the parameter is a positional parameter that exceeds a number, or when a character is appended with a part that is not interpreted as its name. The parameter is a column: [email protected]:~# Echo ${path}/usr/local/sbin:/usr/local/bin: /usr/sbin:/usr/bin:/sbin:/bin [email protected]:~# ${parameter:-word} uses the default value if Para                Meter is not defined or the value is null is replaced with Word, otherwise the value column for parmeter: [email protected]:~# Echo ${path:-w} #PATH不为空 /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin [email protected]:~# Echo ${PA T:-W} # Pat is empty w [email protected]:~# ${parameter:=word} assigns to parameter Value default value, if parameter is empty or undefined, word is assigned to Parmaeter, otherwise the value is unchanged and the value of parameter is not changed. Special character and positional parameters do not apply to columns: [email protected]:~# Echo ${pat:=w} w [Emai      l protected]:~# Echo ${pat} w [email protected]:~# Echo ${path:=w}          /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin [email protected]:~# ${p Arameter:?word} If parameter is undefined or empty, the output (standard error) is an error in Word, otherwise the output parameter Value column: [EMAIL&N bsp;protected]:~# echo ${p:?              Error} # P undefined-bash:p: error [email protected]:~# ${parameter:+word}  Use alternative values.                If parameter is empty or undefined, the output is empty, otherwise the word column is output: [email protected]:~# echo ${p:+error} [email protected]:~# Echo ${path:+error} ERROR [email protected]:~# ${param Eter:offset} ${parameter:offset:length} substring extension, starting at offset position, output length characters if the offset is calculated as a number less than 0, the value is used as the parameter            The offset of the character at the end of the value. If the length is evaluated for a number less than 0, it is interpreted as an offset from the end character of the parameter value (not multiple characters), and the extension is the character between the offset and the result.                Note that a negative offset must be at least one space separated from the colon. If length is unspecified, the character of the 0-offset position will be deleted if the parameter is @, then the result is the start offset of the length position parameter.          Relative to the largest bit    parameter, a negative offset is taken away, so the offset of 1 is equal to the last positional parameter.              If the length is calculated as a number less than 0, the expansion error. If the parameter is an indexed array name written by @ or *, the result is that the length member of the array begins with ${pa Rameter[offset]}. A negative offset is used relative to the maximum index of the specified array.              If the length is calculated as a number less than 0, the expansion error.              A substring extension applied to an associative array produces undefined results. The substring index is zero-based, unless a positional parameter is used, in which case the index starts at 1 by default.              If the offset is 0 and the positional parameter is used, the $ A is pre-pinned to the list. Column: [email protected]:~# Echo ${path:2} sr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin: /sbin:/bin [email protected]:~# Echo ${path:2:4} sr/l [Email protec                ted]:~# ${!prefix*} ${[email protected]} variable name matching, matching variable names starting with prefix, output matching variable names: [email protected]:~# Echo ${! p*} PAT PATH pipestatus PPID PS1 PS2 PS4 PW PWD [email protected]:~# Echo ${[email&nbsp ;p rotected]} PAT PATH pipestatus PPID PS1 PS2 PS4 PW PWD [email protected]:~# ${!name[@]} ${!name[*]} The list of array keys. If the name is an array variable, it expands to the list of array indexes (keys) specified in the name. If the name is not an array, it is expanded to 0, or null if the name is set to N ull.                When @ is used, the extension appears in double quotation marks, and each key expands to a single word. For example: [email protected]:~# echo ${name[@]} 1 2 [Email pro              tected]:~# Echo ${!name[@]} 0 2 [email protected]:~# ${#parameter}                The variable length, if the variable is undefined or empty, returns 0 if an array variable returns the array length for example: [email protected]:~# echo ${#PATH} [email protected]:~# ${parameter#word} ${parameter# #word} prefix matching modulo , if the value of parameter begins with Word, word parameter before will be deleted, and if parameter is an array variable, like ${parameter[@] #word}, then each value in this array will be prefixed with word.                    Word for the shortest match # #word for the longest match for example: [email protected]:~# Echo ${path#/usr} /local/sbin:/usr/local/bin:/uSr/sbin:/usr/bin:/sbin:/bin [email protected]:~# ${parameter%word} ${parameter%%word}                    In contrast to ${parameter#word}, the suffix matches for example: [email protected]:~# Echo ${path%bin}                    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/  [email protected]:~# ${parameter/pattern/string} mode substitution, Pttern will be replaced with string normal pattern Only the first match will be replaced with a string if the expression begins with #, such as: #w, you must match the expression with a number that starts with W, if it is t%, you must match the pattern support pass with the end of T                    *, such as: ${pwd/*/s}, the value of the variable PWD is all replaced by s if parameter is an array variable, the members of the array do this and return a number of matching results, such as the following: [email protected]:~# [email protected]:~# Echo ${path/#\/usr/s} s/l Ocal/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin [email protected]:~# ${parameter^pat Tern} ${parameter^^pattern} ${parameter, pattern} ${parameter,,pattern} uppercase and lowercase conversions.              ^ Operation converts pattern matching result to uppercase, first character, action converts pattern match result to lowercase, first character ^^ operation converts pattern match result to uppercase letter , the operation sends a match of pattern to a lowercase letter if parameter is an array variable, each member of the array will match the pattern with the wildcard character: * in ^^ and, the operation represents 0 or more characters, in ^ and, represents one or 0 characters? Same as * For example: [email protected]:~# Echo ${term,*} xterm [EMAIL&N                 bsp;protected]:~# Echo ${term^*} Xterm [email protected]:~# Echo ${term^^*} XTERM [email protected]:~# Echo ${term,,*} XTERM [Email prot  ected]:~#
Resources
    • The difference between the set, Env, declare, and export display shell variables in Linux

Shell Programming (iv): variables

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.