02Shell variable

Shell Variables

What is a shell variable

shell variable is used to represent a fixed character string is not fixed content

Type of the variable

Custom Variables

Define the variable

变量名=变量值 (显式赋值)

变量名必须以字母或下划线开头,区分大小写

ip1=192.168.2.115
Explicit assignment
[root@hadoop04 shell]# cat ping.sh 
#!/usr/bin/bash

# 显式赋值
ip=172.16.1.12

ping -c1 $ip &> /dev/null 

if [ $? -eq 0 ];then
  echo -e "\e[32m$ip is up\e[0m" 
else
  echo -e "\e[31m$ip is down\e[0m"
fi
Implicit Assignment
[root@hadoop04 shell]# cat ping01.sh 
#!/usr/bin/bash

# 从键盘读入,赋值给变量ip(隐式赋值)

#read ip

# -p选项,提示输入

read -p "Please input a ip: " ip

ping -c1 $ip &> /dev/null 

if [ $? -eq 0 ];then
  echo -e "\e[32m$ip is up\e[0m" 
else
  echo -e "\e[31m$ip is down\e[0m"
fi

Reference variable

1.$变量名

2.${变量名}

View Variable

1.echo $变量名 

2.set  显示所有变量,包括自定义变量和环境变量

Cancel variables

unset 变量名
注意:unset后面跟的是变量名,不带$

Scope

作用范围:仅在当前 shell 中有效

Environment Variables

Define environment variables

#方法1 
export back_dir1=/home/backup1
#方法2,将自定义变量转换成环境变量
back_dir2=/home/backup2
export back_dir2 

Reference environment variables

1.$变量名

2.${变量名}

View the environment variables

echo $变量名 
env  例如 env |grep back_dir2

Cancellation environment variables

unset 变量名
注意:unset后面跟的是变量名,不带$

Variable scope

变量作用范围: 在当前 shell 和子 shell 有效

In a real project, not specifically recommended to define an environment variable, recommended way: Define public variables in a common script, when you want to use public variables, only public execution in the current script script ( . public.sh)

=====================================================

C 语言 局部变量 vs 全局变量

SHELL 自定义变量 vs 环境变量

=====================================================

Position variable

$1 $2 $3 $4 $5 $6 $7 $8 $9 ${10}

[root@hadoop04 shell]# cat ping02.sh 
#!/usr/bin/bash

ping -c1 $1 &> /dev/null 

if [ $? -eq 0 ];then
  echo -e "\e[32m$1 is up\e[0m" 
else
  echo -e "\e[31m$1 is down\e[0m"
fi

# 虽然传了两个变量,但是此脚本中只引用了$1
[root@hadoop04 shell]# bash ping02.sh 172.16.1.12 172.22.34.1
172.16.1.12 is down

Predefined variables

$0 脚本名
$* 所有的参数
$@ 所有的参数
$# 参数的个数
$$ 当前进程的 PID
$! 上一个后台进程的 PID
$? 上一个命令的返回值 0 表示成功  

Examples

Example 1

[root@hadoop04 shell]# cat test.sh 
#!#/usr/bin/bash
echo "第 2 个位置参数是$2"
echo "第 1 个位置参数是$1"
echo "第 4 个位置参数是$4"

echo "所有参数是: $*"
echo "所有参数是: $@"
echo "参数的个数是: $#"
echo "当前进程的 PID 是: $$"

echo '$1='$1
echo '$2='$2
echo '$3='$3
echo '$*='$*
echo '$@='$@
echo '$#='$#
echo '$$='$$

[root@hadoop04 shell]# bash test.sh A B C D E F
第 2 个位置参数是B
第 1 个位置参数是A
第 4 个位置参数是D
所有参数是: A B C D E F
所有参数是: A B C D E F
参数的个数是: 6
当前进程的 PID 是: 11742
$1=A
$2=B
$3=C
$*=A B C D E F
$@=A B C D E F
$#=6

Example 2

[root@hadoop04 shell]# vim ping03.sh
#!/usr/bin/bash

#如果用户没有加参数
if [ $# -eq 0 ];then
  echo "usage: `basename $0` file"
  exit
fi

#如果传入的参数不是文件
if [ ! -f $1 ];then
  echo "$1 is not file"
  exit
fi

for ip in `cat $1`
do
  ping -c1 $ip &> /dev/null
  if [ $? -eq 0 ];then
    echo -e "\e[32m$ip is up\e[0m" 
  else
    echo -e "\e[31m$ip is down\e[0m"
  fi
done

[root@hadoop04 shell]# cat ip.txt 
172.22.34.10
172.22.34.20
172.22.34.30

[root@hadoop04 shell]# bash ping03.sh ip.txt 
172.22.34.10 is down
172.22.34.20 is up
172.22.34.30 is up

Variable assignment mode

Explicit assignment

Variable name = variable value

Examples

ip1=192.168.1.251
school="BeiJing 1000phone"  

today1=`date +%F`
today2=$(date +%F)  

read variable value read from the keyboard

read variable names

# -p选项,提示信息
read -p "提示信息: " 变量名

# -t选项,等待输入时间,单位为秒s
read -t 5 -p "提示信息: " 变量名

#-n选项,限制字符
read -n 2 变量名  

Examples

[root@hadoop04 shell]# vim input.sh
#!/usr/bin/bash

read -p "输入姓名,年龄,性别[e.g. zhangsan 29 m]: " name age sex

echo "您输入的姓名: ${name},年龄: ${age},性别: ${sex}"

[root@hadoop04 shell]# bash input.sh 
输入姓名,年龄,性别[e.g. zhangsan 29 m]: sek 29 w
您输入的姓名: sek,年龄: 29,性别: w

Precautions

Note the definition or reference variables

1." " 弱引用

2.' ' 强引用  

3.` ` 命令替换 等价于 $() 反引号中的 shell 命令会被先执行  

Variable operations

Integer arithmetic

方法1: expr
expr 1 + 2
expr $num1 + $num2        加+ 减- 乘\* 除/ 取余%

☆方法2: $(())
echo $(($num1+$num2))     加+ 减- 乘* 除/ 取余%
echo $((num1+num2))

echo $((5-3*2))
echo $(((5-3)*2))
echo $((2**3))
sum=$((1+2)); echo $sum

方法3: $[]
echo $[5+2]                + - * / %
echo $[5**2]

☆☆方法4: let
let sum=2+3; echo $sum
let i++; echo $i  

Examples

Example 1

[root@hadoop04 shell]# vim mem_usage.sh
#!/usr/bin/bash
mem_used=`free -m | grep Mem | awk '{print $3}'`
mem_total=`free -m | grep Mem | awk '{print $2}'`
mem_percent=$((100*mem_used/mem_total))
echo "当前的内存使用率是${mem_percent}%"

[root@hadoop04 shell]# bash mem_usage.sh
当前的内存使用率是3%

Example 2

[root@hadoop04 shell]# vim ping04.sh
#!/usr/bin/bash

ip=172.22.34.18

i=1

while [ $i -le 5 ]

do

  ping -c1 $ip &> /dev/null

  if [ $? -eq 0 ];then
    echo -e "\e[32m$ip is up\e[0m" 
  else
    echo -e "\e[31m$ip is down\e[0m"
  fi

  let i++

done
[root@hadoop04 shell]# bash ping04.sh
172.22.34.18 is up
172.22.34.18 is up
172.22.34.18 is up
172.22.34.18 is up
172.22.34.18 is up

Decimal arithmetic

If you do not install the calculator, you need to install

[root@hadoop04 ~]# yum -y install bc

Computed style

1.bc
echo "2*4" |bc
echo "2^4" |bc
echo "scale=2;6/4" |bc
2.awk
awk 'BEGIN{print 1/2}'
3.python
echo "print 5.0/2" |python  

Improvement Example 1 above

[root@hadoop04 shell]# vim mem_usage.sh
#!/usr/bin/bash
mem_used=`free -m | grep Mem | awk '{print $3}'`
mem_total=`free -m | grep Mem | awk '{print $2}'`
mem_percent=`echo "scale=2;100*$mem_used/$mem_total" | bc`
echo "当前的内存使用率是${mem_percent}%"

[root@hadoop04 shell]# bash mem_usage.sh 
当前的内存使用率是3.95%

Variable "content" remove and replace

Delete "content"

Standard View

${变量名}

Examples

[root@hadoop04 ~]# url=www.sina.com.cn
[root@hadoop04 ~]# echo ${url}
www.sina.com.cn

Get value of a variable length

${#变量名}

Examples

[root@hadoop04 ~]# url=www.sina.com.cn
[root@hadoop04 ~]# echo ${#url}
15

Front to back, shortest match

${string#substring}

string can be a string, or a string variable name

i.e., substring substring

$ {string # substring} means to delete from the beginning of the substring of string (the substring matching 最短substring)

Non-greedy match

Examples

[root@hadoop04 ~]# url=www.sina.com.cn
# 与“*si”匹配的最短子串是“www.si”
[root@hadoop04 ~]# echo ${url#*si}
na.com.cn
# 与“*.”匹配的最短子串是“www.”
[root@hadoop04 ~]# echo ${url#*.}
sina.com.cn

Front to back, the longest match

${string##substring}

$ {string ## substring} substring represented deleted (with matching substring from the beginning of the string 最长substring)

Greed match

[root@hadoop04 ~]# url=www.sina.com.cn
# 与“*.”匹配的最长子串是“www.sina.com.”
[root@hadoop04 ~]# echo ${url##*.}
cn

From the back, the shortest match

${string%substring}

string can be a string, or a string variable name

i.e., substring substring

$ {string% substring} represents removed from the string at the end of the substring (the substring matching 最短substring)

Non-greedy match

[root@hadoop04 ~]# url=www.sina.com.cn
# 与“.*”匹配的最短子串是“.cn”
[root@hadoop04 ~]# echo ${url%.*}
www.sina.com

From back to front, the longest match

${string%substring}

string can be a string, or a string variable name

i.e., substring substring

$ {string% substring} represents removed from the string at the end of the substring (the substring matching 最长substring)

Greed match

[root@hadoop04 ~]# url=www.sina.com.cn
# 与“.*”匹配的最短子串是“.sina.com.cn”
[root@hadoop04 ~]# echo ${url%%.*}
www

Index and sliced

1.string string index starts from 0, is the last index (length - 1)

2. {string: position} expressed from the string to the string of the extracted start position POSITION substring, numerals from 0

3. {string: position: length} represents the name from the first position string string extraction start position of substring of length length

Examples

# 抽取从索引0开始,长度为5的子串
[root@hadoop04 ~]# echo ${url:0:5}
www.s
# 抽取从索引5开始,长度为5的子串
[root@hadoop04 ~]# echo ${url:5:5}
ina.c
# 抽取从索引5开始,到字符串结束的子串
[root@hadoop04 ~]# echo ${url:5}
ina.com.cn

Replace "content"

$ {String / substring / replacement}, and to replace only the first substring match substrings

Non-greedy match

[root@hadoop04 ~]# url=www.sina.com.cn
[root@hadoop04 ~]# echo ${url/sina/baidu}
www.baidu.com.cn
[root@hadoop04 ~]# echo ${url/n/N}
www.siNa.com.cn

$ {String // substring / replacement}, and replacing all substring match substrings

Greed match

[root@hadoop04 ~]# url=www.sina.com.cn
[root@hadoop04 ~]# echo ${url//n/N}
www.siNa.com.cN

Alternatively substring matches a substring at the beginning of the format: $ {string / # substring / replacement}

Non-greedy

[root@hadoop04 ~]# url=www.sina.com.cn
[root@hadoop04 ~]# echo ${url/#www/ftp}
ftp.sina.com.cn
[root@hadoop04 ~]# echo ${url/#w/W}
Www.sina.com.cn

In addition to replacing the substring match substrings at the end of the format: $ {string /% substring / replacement}

Non-greedy

[root@hadoop04 ~]# url=www.sina.com.cn
[root@hadoop04 ~]# echo ${url/%cn/org}
www.sina.com.org

Substitution variables

${变量名-新的变量值}

Variable is not assignment: use the "new variable value" substitution
variables are assigned (including null): will not be replaced

[root@hadoop04 ~]# echo ${var1}
[root@hadoop04 ~]# echo ${var1-aaaaa}
aaaaa

[root@hadoop04 ~]# var2=111
[root@hadoop04 ~]# echo ${var2-bbbbb}
111

[root@hadoop04 ~]# var3=
[root@hadoop04 ~]# echo ${var3-ccccc}
${变量名:-新的变量值}

Variable is not assigned (including null): will use "new variable value" substitute
variables are assigned: will not be replaced

[root@hadoop04 ~]# echo ${var4}
[root@hadoop04 ~]# echo ${var4:-aaaaa}
aaaaa

[root@hadoop04 ~]# va5=111
[root@hadoop04 ~]# echo ${var5:-bbbbb}
111

[root@hadoop04 ~]# var6=
[root@hadoop04 ~]# echo ${var6:-ccccc}
ccccc
${变量名+新的变量值}

Variable is not assignment: will not be replaced
variable has been assigned (including null): use the "new variable value" alternative

${变量名:+新的变量值}

Variable is not assigned (including null): Will not be replaced
variable has been assigned: use the "new variable value" alternative

${变量名=新的变量值}

Variable is not assigned: will use "new variable value" alternative, declare the variables and 变量名=新的变量值
variables are assigned (including null): will not be replaced

${变量名:=新的变量值}

Variable is not assigned (including null): will use "new variable value" alternative, declare the variables and 变量名=新的变量值
variables are assigned (including null): will not be replaced

${变量名?新的变量值}

To be added

${变量名:?新的变量值}

To be added

Reference link: https: //blog.csdn.net/seulzz/article/details/101350452

https://blog.51cto.com/lulucao2006/1734696

https://blog.csdn.net/xy913741894/article/details/74355576

i ++ sum ++ i

i++

先赋值,再运算  

++i

先运算,再赋值  

Impact on the value of variables:没有影响

[root@tianyun ~]# i=1
[root@tianyun ~]# let i++
[root@tianyun ~]# echo $i
2
[root@tianyun ~]# j=1
[root@tianyun ~]# let ++j
[root@tianyun ~]# echo $j
2  

Impact on the value of the expression:表达式的值受影响

[root@tianyun ~]# unset i
[root@tianyun ~]# unset j

[root@tianyun ~]# i=1
[root@tianyun ~]# j=1

[root@tianyun ~]# let x=i++ 先赋值,再运算
[root@tianyun ~]# let y=++j 先运算,再赋值

[root@tianyun ~]# echo $i
2
[root@tianyun ~]# echo $j
2
[root@tianyun ~]# echo $x
1
[root@tianyun ~]# echo $y
2  

Guess you like

Origin www.cnblogs.com/ElegantSmile/p/12014951.html