Let's learn Shell - shell variables

Shell variable

Use a fixed string to represent unfixed content

Type of variable

Custom variable

  • Defining variables: variable name = variable value. Variable names must start with letters or underscores and are case sensitive (example: ip1=192.168.2.115)
  • Reference variable: $variable name or ${variable name}
  • View variables: echo $variable name or set (all variables: including custom variables and environment variables)
  • Cancel variable: unset variable name
  • Scope: valid only in the current Shell

environment variable

  • export JAVA_HOME=/usr/local/java
  • View environment variables
    • env | grep JAVA_HOME
  • Scope of environmental variables
    • Both the current shell and the subshell are valid

local variable

It is generally used in the function to indicate that the variable is only valid in the current function

  • loacl bak_dir="/data_bak/"

Position variable

  • $1,$2,$3,$4,$5,$6...

Predefined variables

  • The file name of the $0 script itself
  • $* all parameters
    • "$*" (with double quotation marks) will output all parameters as a whole in the form of "$1 $2... $n"
  • $@ all parameters
    • "$@" (with double quotation marks) will separate the parameters and output all parameters in the form of "$1" "$2"... "$n"
  • Number of $# parameters
  • $$PID of the current process
  • $! PID of previous background process
  • $? The return value 0 of the previous command indicates success

Assignment method of variable

Explicit assignment

  • Variable name = variable value
path_dir=$(cd $(dirname $0); pwd)
today=$(date +%F)

read reads the variable value from the keyboard

  • read variable name
  • read -p "prompt:" variable name
  • read -t 5 -p "prompt:" variable name
  • read -n 2 variable name
  • Read: Usage: read [-ers] [-a array] [- d separator] [- i buffer text] [- N read characters] [- N read characters] [- p prompt] [- t timeout] [- u file descriptor] [name...]
#!/usr/bin/env bash
bak_dir1=/var/backup
read -p "Please enter your backup directory: " back_dir2
echo $bak_dir1
echo $bak_dir2
#!/usr/bin/env bash
read -p "Please input ipaddress: " ip
ping -c2 $ip >& /dev/null
if [ $? = 0 ];then
    echo "host $ip is ok"
else
    echo "host $ip is fail"
fi

declare

  • Like typeset, both are bash built-in commands, which can not only define variables, but also set the attributes of variables

Syntax format

-Indicates setting properties

+Indicates that the property is cancelled

aAfFgilprtux are all specific options

declare [+/-] [aAfFgilprtux] [Variable name=Variable value]
  • -a set variable to index array
  • -A set the variable as an associative array
  • -f lists the function name and function body previously defined by the user in the script
  • -F lists only custom function names
  • -g create a global variable within a function
  • -i set the variable to integer type
  • -p displays the attributes and variable values of the specified variable
  • -r set the variable to read-only (cannot be deleted or modified), which is equivalent to readonly name
  • -Set x variable as environment variable, which is equivalent to export name=value

Define reference variables

  • '' weak reference
  • '' strong reference
#!/usr/bin/env bash
my_name=$(whoami)
echo "${my_name}"
echo '${my_name}'

After executing the script, the following results will appear

root
${my_name}

When there are variables, the strong reference will not pass the variable value to the variable, but output the content intact. Therefore, the strong reference represents itself. In the process of use, you need to pay attention to the scene

  • ```(backquote) ` command replace
    • Equivalent to $()
    • Shell commands in backquotes are executed first

Operation of variables

Integer operation

  • +Add
  • -Minus
  • *Multiplication (when using expr, use \ * to represent multiplication symbol)
  • /Except
  • %Remainder
expr mode
#!/usr/bin/env bash
a=1
b=1
expr ${a} + ${b}
expr ${a} - ${b}
expr ${a} \* ${b}
expr ${a} / ${b}
expr ${a} % ${b}

Note: there are spaces before and after the operation symbol

How $(())
#!/usr/bin/env bash
a=1
b=1
echo $((${a}+${b}))
echo $((${a}-${b}))
echo $(((${a}*${b})+${a}))
echo $((${a}/${b}))
echo $((${a}%${b}))

Binary to decimal

echo $((2#10011110101110110100010))

Hex to decimal

echo $((16#4f5da2))
How $[] works
#!/usr/bin/env bash
a=1
b=1
echo $[${a}+${b}]
echo $[${a}-${b}]
echo $[(${a}*${b})+${a}]
echo $[${a}/${b}]
echo $[${a}%${b}]
let's approach
#!/usr/bin/env bash
i=1
let i++
echo ${i}

Decimal operation

bc command mode
  • +Add
  • -Minus
  • *Ride
  • /Except
  • %Remainder
  • ^Power (power)
#!/usr/bin/env bash
a=2
b=10
echo "${a}^${b}" | bc
echo "${a}+${b}" | bc
echo "${a}*${b}" | bc
echo "${a}/${b}" | bc
echo "${a}%${b}" | bc
awk mode
awk 'BEGIN{print 2^10}'
python way
echo "print 5.0/2" | python

Deletion of variable "content"

#Match from front to back

##From front to back, greedy matching

%Match from back to front

%%Matching from back to front, greedy matching

. matching characters

*All characters

#!/usr/bin/env bash
test_url='www.GoodGoodStudy.DayDayUp.com'

echo "Standard view: ${test_url}"

echo "Length of variable value: ${#test_url}"

echo "From front to back,Shortest match: ${test_url#*.}"

echo "From front to back,Longest match(Greedy matching): ${test_url##*.}"

echo "From back to front,Shortest match: ${test_url%.*}"

echo "From back to front,Longest match(Greedy matching): ${test_url%%.*}"

give the result as follows

Standard view: www.GoodGoodStudy.DayDayUp.com
 Length of variable value: 30
 From front to back,Shortest match: GoodGoodStudy.DayDayUp.com
 From front to back,Longest match(Greedy matching): com
 From back to front,Shortest match: www.GoodGoodStudy.DayDayUp
 From back to front,Longest match(Greedy matching): www

Greedy matching is to match to the last position of the specified character and delete the content before or after the character

Replacement of variable "content"

Usage: variable name / content before replacement / content after replacement

#!/usr/bin/env bash
test_url='www.GoodGoodStudy.DayDayUp.com'

echo "take com Replace with cn: ${test_url/com/cn}"

echo "take o Replace with O(Greedy matching): ${test_url//o/O}"

give the result as follows

take com Replace with cn: www.GoodGoodStudy.DayDayUp.cn
 take o Replace with O(Greedy matching): www.GOOdGOOdStudy.DayDayUp.cOm

Greedy matching, in fact, is to match all (because we want all, so we are greedy)

Index and slice of variables

#!/usr/bin/env bash
test_url='www.GoodGoodStudy.DayDayUp.com'

echo "The contents of the next five characters starting from the first character: ${test_url:0:5}"

echo "The contents of the next five characters starting from the sixth character: ${test_url:5:5}"

echo "Cut out the content after the first five characters: ${test_url:5}"

give the result as follows

The contents of the next five characters starting from the first character: www.G
 The contents of the next five characters starting from the sixth character: oodGo
 Cut out the content after the first five characters: oodGoodStudy.DayDayUp.com

Substitution of variables

During the practice here, it should be noted that the original assignment of the variable value cannot be cleared through the unset command. Just disconnect the terminal and reconnect

echo ${var:-New variable value} ; echo ${var}
echo ${var:+New variable value} ; echo ${var}
echo ${var:=New variable value} ; echo ${var}

When the variable value is empty

  • : - aaa the value of var variable will be temporarily replaced with aaa, but the value of var variable itself is still null
  • : + aaa the value of var variable will not be temporarily replaced with aaa, but the value of var variable itself is still null
  • : = aaa the value of the VaR variable is directly replaced with aaa and is permanently replaced

When the variable has been assigned

var1=111
  • : - aaa the value of the VAR1 variable will not be temporarily replaced by aaa, and its own assignment will remain unchanged
  • The value of the + aaa var1 variable will not be temporarily replaced by aaa, and its own assignment will remain unchanged
  • : = aaa the value of the VAR1 variable will not be temporarily replaced by aaa, and its own assignment will remain unchanged
  • :? The value of aaa var1 variable will not be temporarily replaced by aaa, and its own assignment will remain unchanged
  • TA has a heart. Don't be greedy for TA's body. TA won't go with you

The difference between i + + and + + i

#!/usr/bin/env bash
i=1
j=1

let k=i++
let l=++j

echo "variable K The value of is: ${k}"
echo "variable l The value of is: ${l}"
echo "variable i The value of is: ${i}"
echo "variable j The value of is: ${j}"

give the result as follows

variable K The value of is: 1
 variable l The value of is: 2
 variable i The value of is: 2
 variable j The value of is: 2

i + + assign values first and then operate

++i operation before assignment

For simple variables, there is no effect between the two

However, for expressions, the final variable values are different

Keywords: Linux shell bash

Added by daijames on Mon, 24 Jan 2022 05:13:22 +0200