Linux Shell variable and linuxshell variable
Introduction
Variables are an essential part of shell scripts. You do not need to declare them in advance when using variables in scripts. Every variable in bash is a string, so no matter whether quotation marks are used for variable assignment, they are stored in the form of strings. However, if a value contains special characters, you need to quote the value with quotation marks, single or double quotation marks can be used in bash.
Environment: centos 6.7
Assignment
Assign a value to the variable:
Var = value
Note that no space exists between variables and values. Otherwise, it will be considered as equivalent judgment, for example, [var = value]
To call a variable, you only need to add $
Output variable:
Echo $ value or echo $ {value}
Example: Write a shell script to output the date of today
Vim assign
#!/bin/bashvar=`date +'%Y-%m-%d'`echo "today is $var"
Operation
[], ()
Note that the above two methods are fixed and are used to perform arithmetic operations in shell, and $ is required before these two operators, you can use $ or not before the variable in the brackets.
#!/bin/bashvar1=1var2=2result1=$[var1+var2]result2=$[$result1+1]result3=$((result2+1))result4=$(($result3+1))echo $result1 $result2 $result3 $result4
In the shell environment, you can use let, [], () to perform basic arithmetic operations.
Let
Let's arithmetic operations include that let itself can also assign values.
Method 1: simple arithmetic operation
var1=1var2=2let result=var1+var2
Method 2: auto-Increment
Let var2 ++ is equivalent to let var2 = var2 + 1
Method 3: abbreviated
Let var2 + = 2 is equivalent to let var2 = var2 + 2
Script
#!/bin/bashvar1=1var2=2let result=var1+var2let var2++let var1+=5printf "var1=1 var2=2 \n"printf "%-10s %-8s %-6s\n" var1+var2 var2++ var1+=5printf "%-10s %-8s %-2s \n" $result $var2 $var1let var=5echo $var
Note: The addition operation is only tested. It is supported for other arithmetic operations, but only supports integer operations. It is not supported for decimal operations.
Advanced Operations bc
Supports decimal operations
Syntax
echo " " | bc
If you want to use the result of the bc operation as a variable
result=`echo " " | bc `
#!/bin/bashecho "0.5*10" | bcvar=5result=`echo "$var*0.5" | bc`echo $result
Summary
The assignment algorithm is still relatively simple and will be improved later
|
Note:
Author: pursuer. chen
Blog: http://www.cnblogs.com/chenmh
All essays on this site are original. You are welcome to repost them. However, you must indicate the source of the article and clearly give the link at the beginning of the article.
Welcome to discussion |