Shell variable assignment and environment

Source: Internet
Author: User
Tags arithmetic

Tag: Replace pattern match shell variable assignment

Shell variable assignment and environment

Today, with the architect (Fan) doing a code-count script, I learned the following:

1) command in script, just string, longer command can be changed to variable, reference to execute

2) Subconscious I think of if, add a block of statements, and Fan but think of grep-v, save a large piece of code

3) echo ' > Stat He naturally added this line, allowing output to be separated by different blocks, with a clear structure

4) He was very impressed with the precise and fast positioning of the problem.


Tonight about the shell variables, I've done a lot of testing, sorting them out as follows so that I know what's new.


#赋值 #

# hours_per_day=24 seconds_per_hour=3600 days_per_week=7# echo  $hours _per_day $ seconds_per_hour  $days _per_week24 3600 7readonly  to make variables read-only and to assign values to them is forbidden # readonly  hours_per_day seconds_per_hour days_per_week # hours_per_day=2-bash: hours_per_ day: readonly variable# echo  $hours _per_day  $seconds _per_hour  $days _per_week24  3600 7export [-fn] [name[=word]] ...   used to create (empty also can), modify, delete, print "Environment" (Environment) export -p      the supplied names are  marked for automatic export to the environment of subsequently  executed commands.   "The provided names is marked as an environment that is automatically exported to subsequent execution commands. "      if the -f option is given, the names  refer to functions.    if the-f,names reference function is specified. (that is, the function name is the variableName)   If no names are given, or if the -p option   is supplied,  a  list  of  all  names that  are exported in this shell is printed.     If no names is given or provided with the-P option, a list of all names is exported (listed) in this shell   the -n option causes the  export property to be removed from each name.     If the-n option causes the property to be removed from each name. (It is not actually deleted, it is not exported to the execution environment of the subsequent instruction, or it is present in the current shell)   if a variable name is followed  by =word, the value of the variable  is  set   to word.  export returns an exit status of 0 unless  an invalid option is encountered,      one of  the names&nBsp;is not a valid shell variable name, or -f is supplied  with a name that is not  a  func‐tion.    If the variable name is followed by =word, the value of the variable is set to Word,export and the return status code is 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or the-f is supplied with a name other than a function.     export is to put the variable into the environment (environment), the environment is a simple list of name and word that can be used by all executing programs.    The new process integrates the environment from its parent process, or it can be modified before a new child process is established.    such as   path= $PATH:/usr/local/bin update Path  export path export it (publish it)   $ export -p  shows the current environment   env [-i] [ var=value&nbsp ...]  [ command_name [ arguments... ] ]-i  ignores inherited environments, using only the variables and values given on the command line. When Command_name is not provided, the name and value of all variables in the environment are displayed, otherwise they are copied using the variables provided on the command line. such as:$ cat test.sh         echo  $HOSTNAME          env        $$ env -i  hostname=30 path=/bin:/usr/bin/  name=abc sh test.sh  (ignoring the inheritance environment, Use only the variables and values provided by the command line)     30    HOSTNAME=30    NAME=ABC     PATH=/bin:/usr/bin/    PWD=/home/zhangchunyang     shlvl=1    _=/bin/env        $ env  HOSTNAME=30 PATH=/bin:/usr/bin/ sh test.sh | less  (Inherit environment, overwrite with same name)      30    hostname=30    pyenv_root=/home/zhangchunyang/ .pyenv    shell=/bin/bash    term=xterm     Histsize=5    catalina_home=/usr/local/tomcat    ssh_client= 117.131.199.244 31299 22    sybase_jre7=/home/opt/sybase/shared/jre-7_0_21_64bit     luajit_lib=/usr/local/lib    python_egg_cache=/tmp/.python-eggs         Note: When printing, Env does not correctly enclose the value of the environment variable in quotation marks for re-entry into the shell, if this function is required, use the export -p    unset [-v]  variable ...  unset -f function ...     removing variables and functions from the current shell     can be any variable (local variable, environment variable)         -f:  dismiss (delete) the specified function      -v:  Dismiss (delete) the specified variable.   When there are no options, this is the default behavior pattern          such as:         unset full_name              Delete Full_name        unset -v first middle last    Delete these variables               who_is_ on  ()  {            who | awk  ' {print $1} '  | sort -u        }         ...                 unset -f who     Delete Functions                  $ cat test.sh          a=1        b=2         c=3        d=4         e=5        f=6                 who_is_on  ()  {              who | awk  ' {print $1} '  | sort -u        }                 unset -v b                 unset -f who_is_on                 echo  $a   $b   $c   $d   $e   $f         who_is_on                 $ sh test.sh          1 3 4 5 6        test.sh:  line 14: who_is_on: command not found                 $ unset PATH         $ ls        -bash: ls: no such file or directory         $ vim        -bash:  vim: no such file or directorydeclare [-aaffgilrtux] [-p] [name[ =VALUE]&NBSP, ...]     #查看变量属性typeset  [-aaffgilrtux] [-p] [name[=value]&nbsp ...]      declaration/Announcement   Variable     -a     each name  is an indexed array variable  (see arrays above)   Declaration name is an indexed array variable     -A     Each name is an associative  array variable  (see arrays above) .  declaration name is an associative array variable     -f      Use function names only.  Use function name     -i      the variable is treated as an integer; arithmetic evaluation  (see  Arithmetic evaluation above)  is               performed when the variable is assigned a value.   declares an integer variable. When a variable is assigned a value, it is represented as an arithmetic evaluation.         -l     when the variable  is assigned a value, all upper-case characters  are   converted  to  lower-case.               The upper-case attribute is disabled.  disable uppercase, the assigned capitalization is automatically lowercase      -r     Make  names readonly.  These  names cannot then be assigned values by subsequent assignment  state‐&Nbsp;             ments or unset.   is set to read-only variables. These names cannot be subsequently redistributed (modified) and deleted (unset)     -t     Give each  Name the trace attribute.  traced functions inherit the debug  and RETURN traps from the               calling shell.  the trace attribute has no  special meaning for variables.    to Name trace Properties      -u     When  the  variable  is   assigned a value, all lower-case characters are converted to  upper-case.              the  Lower-case attribute is disabled.  disables lowercase, and the assigned value is lowercase automatically to uppercase     -x     mark names  for export to subsequent commands via the environment.  Mark names for export to the next command environment             -x  IE export   Published variables                          # export -p | less              declare -x histcontrol= "Ignoredups"              declare -x histsize= " "            declare -x histtimeformat= "%F  %t:%t "            declare -x home= "/root"             declare -x hostname= "Webserver"              ...                         $ declare  -u f            $ f= ' SDAFSADF '              $ declare -u                          declare -u f= "SDAFSADF"                   the above properties can be superimposed               such as declare -irx uid= "0"
  1. Parameter unwinding (parameter expansion) is the procedure that the shell uses to provide variable values in a program.

1) #引用变量值 #
# reminder= ' time to go to the dentist! '     # echo  $reminder     Time to go to  the dentist!        # echo _${reminder}_     #使用 {} can protect variables and avoid additional character impact variables.     _Time to go to the dentist!_          warning:  Default, undefined variables are expanded to null (an empty string). The process of random writing can lead to disaster:                             # rm -fr /$ myprogram         If the MyProgram is not set, there will be a major disaster happened!                  So, write the program very carefully.
2) #替换运算符 # Test the existence state of the string variable and, in some cases, allow the default value to be replaced.
operator Replace Example Use
${varname:-word} Returns the value of VarName if it exists and is not null; # echo ${var:-hello,world} var is not empty, return its value; otherwise, return Hello,world If the variable is not defined, the default value is returned
${varname:=word} Returns the value of a varname if it exists and is not null; otherwise, set it to Word and return its value # echo ${var:-hello,world}; Returns its value if Var has a value; otherwise, returns Hello,world and assigns a value to Var If the variable is undefined, set the variable to the default value
${varname:?message} If varname exists and is not NULL, its value is returned; otherwise, Varname:message is displayed and the current command or script exits. Omitting the message, the default message appears parameter null or not set. ${count:? " UNDEFINED/1 "} will display count:undefined!, if count is undefined, exit To catch errors that are caused by undefined variables.
${varname:+word} Returns word if varname exists and is not NULL, otherwise NULL is returned. If count is already defined, ${count:+1} returns 1 (that is, "true") exists for test variables
3)   #模式匹配运算符 #      mode is ' wildcard character (wildcard) '      basic wildcard character:         ?        any single character         *         any character string         [set]    Any character in set         [!set]   any character not in set       such as:        [abc]          [.,;]   periods, commas, or semicolons (awk  multi-character segmentation)         [-_]   dashes or underscores          [a-c]        [a-z]         [!0-9]  any one non-numeric character          [0-9!]   Any one number or exclamation         [a-za-z0-9_-]${variable#pattern}  Delete variable left-to-right shortest match ${variable# #pattern}  Delete variable left-to-right longest match ${variable%pattern}  Delete variable right-to-left shortest match ${variable%%pattern} delete variable right-to-left longest match


Additional:

Git is not familiar, I can only help Fan the last part, his part without his permission, or do not write.

For name in ' ls $respath |grep-v gitresult ' dosort-u $respath/$name | while read commit; Do git show $commit--pretty=tformat:--numstat;done | Awk-v user= $name ' {add + = $ subs + = $ = $ $ + $ + $ + $ + $ + $ + $ + $ + $ = $ + + + + + NES:%s\n ", user, Add, Subs, loc} ' >> $respath/gitresult. $since. $beforedone-------Tips------path=$1respath=/home /zcyrespath= "$respath/${path:-result}" if $ $ is empty, then respath=/home/zcy/result; otherwise, respath=/home/zcy/$path


This article is from the "zcy.gy" blog, make sure to keep this source http://1064187464.blog.51cto.com/9108437/1904980

Shell variable assignment and environment

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.