Shell variables released the positional variables and predefined variables.

Source: Internet
Author: User
Tags add numbers

Shell variables are divided into 3 parts, namely user-defined variables, positional variables, and predefined variables.

I. Custom variables

So, what is a variable? To put it simply, a particular string represents an invariant content, and user-defined variables are the most common shell variables. Y=3A+2B, is to give 3a+2b this value to Y. Variable names start with a letter or a line break, and you can add numbers from the second digit, and the uppercase and lowercase letters have different meanings. such as Dir and Dir are different variables. The length of the variable name is not restricted. Expert=bill, for example, is assigning bill to an expert, and later when the script reads the variable $expert, it takes a value of bill

Attention!!!

    1. In an assignment statement, there can be no space on either side of the assignment number "=", or it will cause an error when executed, and there is no python cool. If you want to include spaces, tabs, or line breaks in the value assigned to a variable, enclose the string in double quotation marks. For example, names= "ABC DD FF"
    2. Variables can use numbers, uppercase and lowercase letters, underscores, but cannot start with a number.

You can assign the execution result of a command to a variable. There are two forms of command substitution: one is to use the inverted quotation mark (the case below the ESC) to refer to the command, in the general form: ' Command '. Same as $ (command)

For example, to store the full pathname of the current working directory in the variable dir, enter the following command line:

$ Dir= ' pwd '

Another form is: $ (Command table). The above command line can also be rewritten as:

$ dir=$ (PWD)

Interactive variables

The Read command allows you to read data from the keyboard and assign it to the specified variable. The general format of the Read command is: read [variable 1] [variable 2] ... For example:

If you need to prompt for user input, you can use the-p parameter such as

" Please input the info to user "  

When you enter data, the data is separated by a space or a tab character. If the number of variables is the same as the given number of data, then the corresponding assignment, if the number of variables is less than the number of data, the assignment from left to right, but the last variable is given to all remaining data, if the number of variables more than the given number of data, then the corresponding assignment, and no data corresponding to the variable empty string.

All examples of custom variables are as follows.

[[email protected] Hadoop]#VI variable.sh#!/bin/bashExpert=bill#Assign a value to a variable expertEcho$expert     #the value of the output expert2ndexp=neo#assignment to variable 2ndexp failed with reason: variable name starts with a numberEcho$2ndexpThirdexp=adm Smith#assignment to variable thirdexp failed because of a space on the right side of the equal signEcho$thirdexpLsdir= ' Ls/home '#assigns the return value of the Ls/home command to the variable LsdirEcho$lsdirRead-P"Please Input the favorite 3 letters:"FL1 FL2 FL3#get interactive variables with the Read commandEcho"The letters you input is: $FL 1 $FL 2 $FL 3"    #Output Interaction Variables

Run results

[[email protected] Hadoop] # ./variable.sh Bill. /variable.sh:line 5:2ndexp=Neo:command not foundndexp. /variable.sh:line 83 letters:a b cthe letters you input is:a b c

Here are two important variables, one is the positional variable and the other is the predefined variable.

Two Positional variables

You can have parameters when executing a linux command or shell script. Accordingly, there should be a variable in the shell script. When executing shell programs, use arguments to replace these variables.

The names of such variables are very special in shell scripts, which are 0, 1, 2 ... Such variables are called positional variables because they correspond to the actual arguments on the command line: the command name (script name) corresponds to the position variable 0, the first argument corresponds to the position variable 1, the second argument corresponds to the position variable 2 ... If positional variables are made up of two or more digits, they must be enclosed in a pair of curly braces, such as {10}, {11}. The command line actually participates in the corresponding relationship of positional variables in the script.

A simple example:

[[email protected] Hadoop] #  #!/bin/bash"Theletters you are: $ $ $"    # Output 3 Positional parameters

Run results

[[email protected] Hadoop] # ./variable.sh Z W J      #运行脚本 with 3 parameters $1=z, $2=W, $3=j
The letters you like Is:z W J

Another example: Restart the Network Service command,/ETC/INIT.D/HTTPD Status,status is the/etc/init.d/httpd status command of the first positional variable parameter, the same position variable can use the parameter start, stop and so on, Let's take a look at what this script looks like.

[[email protected]/]#cat/etc/init.d/httpd | grep-v ^# |grep-v ^$case "$"   in start) start;        stop)  stop;;        status) Status-P${pidfile} $httpdRETVAL=$?        ;;        restart)  Stop start; Condrestart |try- restart)ifStatus-p${pidfile} $httpd>&/dev/null; then stop start fi;;   Force-reload| Reload) reload;; Graceful | Help|configtest|fullstatus)$apachectl[Email protected]RETVAL=$?        ;; *) echo$"Usage: $prog {start|stop|restart|condrestart|try-restart|force-reload|reload|status|fullstatus|graceful| Help|configtest}"RETVAL=2Esacexit$RETVAL

Here is a case where the value of the first positional variable and the corresponding action are taken.

Three Pre-defined variables

Predefined variables, as the name implies, are pre-set system variables.

$ A reference position variable, which is the NO. 0 variable, which is the name of the current script.

$# the number of actual arguments on the command line.

$* represents all actual argument strings that are actually given on the command line.

$? The return value (also known as an "exit code") after the last command was executed. It is a decimal number. When the command executes successfully, the return value is 0, and a non-0 value is returned if the execution fails. (different failures have different return values)

$$ the PID process number of the current process.

A simple example:

[[email protected] Hadoop]#VI variable.sh#!/bin/bashEcho"The letters is: $ $ $"   #parameters for output position variablesEcho $                                    #Output Script nameecho $##输出参数数量, the correct output is 3Echo $*#output All parameters the correct output is ZN CN SJecho $?#outputs the return value of the previous command (Echo $*) (correct)#the last command was "print the members of the parameter"Cd/hom#switch to Directory/home, where an error is entered and the command does not take effectecho $?#the previous command (Cd/hom) failed to return a non 0Cd/home/hao#switch to Directory///, enter correct hereecho $?#the previous command (Cd/home) executed successfully, returning 0Echo $$#the PID process number of the current process. 
View Code

Operation Result:

Run Result: [Root@Hao Hadoop] # ./variable.sh Zn CN SJ #运行脚本 with 3 parameters Zn, cn, SJ The letters you like is:zn CN SJ. /variable.sh3ZN CN SJ0. /variable.sh:line 8:CD:/hom:no such file or directory105325
View Code

Another example, where the use of 6 positional variables, some positional variables have a space parameter, here is the way to deal with the parameter space (there are other ways, I did not all listed, specifically what way, we think for themselves).

[[email protected] Hadoop]#VI var_show.sh#!/bin/bashEcho Running File is $              #using the $ output file pathMkdir $                               #take the first parameter/home/sss as the mkdir parameter and create a new folderEcho $is ready Touch $/file. $. txt#take the first and second parameters \ File.$2.txt file path and name as new fileEcho $/file. $. txt is a ready ping $-C 1 >> $/file. $. txt#Ping the third parameter 1 times (in this case, 192.168.0.1), and append the result to the file you just created File.$2.txStr0=$?#赋值给命令返回值, this should return 0echo.>> $/file. $. txt Ping $-M 1 2>> $/file. $. txt#Ping the third parameter 1 times (in this case, 192.168.0.1) but the parameter is wrong (-m), and the error message is appended to the newly created file File.$2.txtstr1=$?Echo>> $/file. $. Txtpang $2>> $/file. $. txt#Ping the third parameter 1 times (in this case 192.168.0.1) but the command error (Pang), and add an error message to the file you just created File.$2.txtstr2=$?Echo>> $/file. $. txt$42>> $/file. $. txt#executes the command, the command is the fourth parameter (in this case the service) but the parameter is wrong, and the error message is appended to the newly created file File.$2.txtStr3=$?Echo>> $/file. $. txt $>> $/file. $. txt#executes the command, the command is the fifth parameter (in this case, service httpd) but the parameter is incorrect, and the error message is appended to the newly created file File.$2.txtSTR4=$?Echo>> $/file. $. txt$6>> $/file. $. txt#executes the command, the command is the sixth parameter (in this case, the service httpd stop and appends the information to the file just created File.$2.txtStr5=$?Echo>> $/file. $. Txtecho$STR 0  $str 1  $str 2 $STR 3 $STR 4  $STR 5     #outputs the return value of all commands. Echo >> $/file. $. Txtecho Now the system would sleep$#seconds.Sleep $##利用预定于变量 $#, take the number of positional parameters and sleep the corresponding number of seconds. echo FINISH!!!

Run commands and Add parameters

[[email protected] Hadoop] # ./VAR_SHOW.SH/HOME/SSS Demo 192.168.0.1 Service ' service httpd ' "Service httpd Stop"
the first parameter of the script is the third parameter , $4 . The space $6 also appears, using single and double quotation marks

View results:

Running File is./var_show.sh/home/sssare ready/home/sss/file.demo.txtare ready 0 2 127 1 2 06 seconds. FINISH!!!
View Code

VI Documents just created

[[email protected] home]#VI sss/file.demo.txtPING 192.168.0.1 (192.168.0.1) 56 (84) bytes of data.Bytes from 192.168.0.1:icmp_seq=1 ttl=64 time=3.02Ms---192.168.0.1 ping Statistics---1 packets transmitted, 1 received, 0%packet loss, time 3msrtt min/avg/max/mdev = 3.026/3.026/3.026/0.000msping:invalid Option--' m ' usage:ping [-LRUBDFNQRVVAA] [-C Count] [-I interval] [-W Deadline] [-P pattern] [-s packetsize] [-t TTL] [-I interface or address] [-M MTU Discovery hint] [-S Sndbuf] [ -t timestamp option] [-Q TOS] [Hop1 ...] Destination./var_show.sh:line 15: Pang:command not foundusage:service < option> | --status-all | [service_name [Command |--full-Restart]] usage:httpd {Start|stop|restart|condrestart|try-restart|force-reload|reload|status|fullstatus|graceful|help|Configtest} Stopping httpd: ^[[60g[^[[0;31mfailed^[[0;39m]^m
View Code

From here, it is essential to have a good command of the shell script, to master and use positional variables and predefined variables.

Shell variables released the positional variables and predefined 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.