Shell脚本编程中的变量

一、什么是变量?

  变量来源于数学,是计算机语言中能储存计算结果或能表示值抽象概念。变量可以通过变量名访问

二、变量的种类有哪些?

本地变量 生效范围为当前shell进程;对当前shell之外的其它shell进程,包括当前shell的子shell进程均无效
环境变量 生效范围为当前shell进程及其子进程
局部变量 生效范围为当前shell进程中某代码片断(通常指函数)
位置变量 $1, $2, …来表示,用于让脚本在脚本代码中调用通过命令行传递给它的参数
特殊变量 :$?, $0, $*, $@, $#

三、变量的详解与使用

   1、本地变量

     定义本地变量的格式:name=‘value’

   2、可以使用引用value定义:

(1) 可以是直接字串; name=“root"
(2) 变量引用:name="$USER"
(3) 命令引用:name=`COMMAND`, name=$(COMMAND)

   3、变量引用:${name}, $name

"" 弱引用,其中的变量引用会被替换为变量值
'' 强引用,其中的变量引用不会被替换为变量值,而保持原字符串

   4、显示已定义的所有变量

export [root@centos6 ~]# exportcd
env [root@centos6 ~]# env
printenv [root@centos6 ~]# printenv


   5、删除变量

[root@centos6 ~]# var=www.mageedu.com

[root@centos6 ~]# echo $var

www.mageedu.com

[root@centos6 ~]# unset var

[root@centos6 ~]# echo $var

[root@centos6 ~]#

(1)环境变量

变量声明、赋值 export name=VALUE
declare -x name=VALUE
变量引用 $name, ${name}
显示所有环境变量 export、env、printenv
删除变量 unset name
bash有许多内建的环境变量 PATH, SHELL, USRE,UID, HISTSIZE, HOME, PWD, OLDPWD, HISTFILE, PS1

(2)只读位置变量

只读变量 可以引用和查看,但不能修改和删除
定义只读变量 readonlyname; declare -r name

(3)位置变量

$1, $2, …: 对应第1、第2等参数,shift [n]换位置
$0 命令本身
$* 传递给脚本的所有参数,全部参数合为一个字符串
$@ 传递给脚本的所有参数,每个参数为独立字符串
$# 传递给脚本的参数的个数

四、位置变量的使用

环境变量的详解

blob.png

区分:$10与${10}的区别

blob.png

区分:$*与$@的区别

blob.png

四、课堂练习和作业

1、编写脚本/root/bin/systeminfo.sh,显示当前主机系统信息,包括主机名,IPv4地址,操作系统版本,内核版本,CPU型号,内存大小,硬盘大小

[root@centos6 tmp]# cat systeminfo.sh 
#!/bin/bash
#

echo "HostName: `hostname`"
echo "IPv4: `ifconfig |sed -n '2p' |cut -d: -f2|cut -d ' ' -f1`"
echo "System Version: `cat /etc/redhat-release`"
echo "Kernel: `uname -r`"
echo "Cpu: `lscpu |grep "name" |tr -s ' '|cut -d ' ' -f5`"
echo "Memory: `free -h|sed -n '2p'|tr -s ' '|cut -d ' ' -f2`"
echo "Hard Disk: `fdisk -l | sed -n '2p' |cut -d' ' -f3,4|cut -d',' -f1`"
 
[root@centos6 tmp]# bash systeminfo.sh 
HostName: centos6
IPv4: 10.1.255.76
System Version: CentOS release 6.8 (Final)
Kernel: 2.6.32-642.el6.x86_64
Cpu: i7-4810MQ
Memory: 1.8G
Hard Disk: 214.7 GB
[root@centos6 tmp]#

2、编写脚本/root/bin/backup.sh,可实现每日将/etc/目录备份到/root/etcYYYY-mm-dd中

[root@centos6 tmp]# cat backup.sh 
#!/bin/bash
#

cp -r /etc/ /root/etc-`date +%F`
[root@centos6 tmp]# crontab -l
0 23 */1 * * /bin/bash /tmp/backup.sh
[root@centos6 tmp]#

3、编写脚本/root/bin/disk.sh,显示当前硬盘分区中空间利用率最大的值

[root@centos6 tmp]# cat disk.sh 
#!/bin/bash
#

echo "Hard disk sda is space utilization: `df -h |grep 'sda*' | tr -s ' '|cut -d' ' -f5 |sort -n | cut -d'%' -f1 |tail -1`"
[root@centos6 tmp]# bash disk.sh 
Hard disk sda is space utilization: 22
[root@centos6 tmp]#

4、编写脚本/root/bin/links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排序

[root@centos6 tmp]# cat link.sh 
#!/bin/bash
#

echo -e "远程主机连接统计为:\n\t连接数\t远程主机IP"
netstat -nt | tr -s ' ' | cut -d' ' -f5 | tr -cs '0-9.' '\n' | egrep '([0-9]+.){3}[0-9]+' | sort | uniq -c | sort -nr | tr -s ' ' '\t'
[root@centos6 tmp]# bash link.sh 
远程主机连接统计为:
	连接数	远程主机IP
	2	10.1.250.48
[root@centos6 tmp]#

5、写一个脚本/root/bin/sumid.sh,计算/etc/passwd文件中的第10个用户和第20用户的ID之和

[root@centos6 tmp]# 
[root@centos6 tmp]# cat sumid.sh 
#!/bin/bash
#

Link1=`sed -n '10p' /etc/passwd |cut -d: -f3`
Link2=`sed -n '20p' /etc/passwd |cut -d: -f3`

echo "第10个用户和第20用户的ID之和: $((Link1+Link2))"
[root@centos6 tmp]# bash sumid.sh 
第10个用户和第20用户的ID之和: 180
[root@centos6 tmp]#

6、写一个脚本/root/bin/sumspace.sh,传递两个文件路径作为参数给脚本,计算这两个文件中所有空白行之和

[root@centos6 tmp]# cat sumspace.sh 
#!/bin/bash
#

Spacetotal1=`grep '^$' $1 |wc -l`
Spacetotal2=`grep '^$' $2 |wc -l`

echo "$1和$2空白行之和为: $((Spacetotal1+Spacetotal2))"

[root@centos6 tmp]# bash sumspace.sh /etc/fstab /etc/issue
/etc/fstab和/etc/issue空白行之和为: 2
[root@centos6 tmp]#

7、写一个脚本/root/bin/sumfile.sh,统计/etc, /var, /usr目录中共有多少个一级子目录和文件

[root@centos6 tmp]# 
[root@centos6 tmp]# cat sumfile.sh 
#!/bin/bash
#

Etctotal=`ls -a /etc |wc -l`
Vartotal=`ls -a /var |wc -l`
Usrtotal=`ls -a /usr |wc -l`


echo "Sumfiletotal: $((Etctotal+Vartotal+Usrtotal))"
[root@centos6 tmp]# bash sumfile.sh 
Sumfiletotal: 292
[root@centos6 tmp]#

8、写一个脚本/root/bin/argsnum.sh,接受一个文件路径作为参数;如果参数个数小于1,则提示用户“至少应该给一个参数”,并立即退出;如果参数个数不小于1,则显示第一个参数所指向的文件中的空白行数

[root@centos6 tmp]# 
[root@centos6 tmp]# cat argsnum.sh 
#!/bin/bash
#

[ $# -lt 1 ] && echo "At least to a argument" || grep '^$' $1|wc -l 
[root@centos6 tmp]# bash argsnum.sh 
At least to a argument
[root@centos6 tmp]# bash argsnum.sh /etc/fstab 
1
[root@centos6 tmp]#

9、写一个脚本/root/bin/hostping.sh,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping通,则提示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”

[root@centos6 tmp]# cat hostping.sh 
#!/bin/bash
#

ping -c1 -W1 $1 &>/dev/null && echo "The $1 address can access." || echo "The $1 address can not access."
[root@centos6 tmp]# bash hostping.sh 10.1.0.1
The 10.1.0.1 address can access.
[root@centos6 tmp]# bash hostping.sh 10.1.0.0
The 10.1.0.0 address can not access.
[root@centos6 tmp]#

10、chmod -rw /tmp/file1,编写脚本/root/bin/per.sh,判断当前用户对/tmp/fiile1文件是否不可读且不可写

[root@centos6 tmp]# su - wang
[wang@centos6 ~]$ ls -l /tmp/file1
----------. 1 root root 1 Aug  7 10:30 /tmp/file1
[wang@centos6 ~]$ cat /tmp/per.sh
#!/bin/bash
#

[ -r /tmp/file1 -a -w /tmp/file1 ] && echo "`whoami` can  wrint and read" || echo "`whoami` can not wrint and read"
[wang@centos6 ~]$ bash /tmp/per.sh
wang can not wrint and read
[wang@centos6 ~]$

11、编写脚本/root/bin/nologin.sh和login.sh,实现禁止和充许普通用户登录系统

[root@centos6 tmp]# cat login.sh 
#/bin/bash
#

[ -f /etc/nologin ] && (rm -f /etc/nologin;echo user enable login) || echo user disable login already
[root@centos6 tmp]# bash login.sh 
user disable login already

作业:

1、编写脚本/root/bin/systeminfo.sh,显示当前主机系统信息,包括主机名,IPv4地址,操作系统版本,内核版本,CPU型号,内存大小,硬盘大小

[root@centos6 tmp]# cat systeminfo.sh 
#!/bin/bash
#

echo "HostName: `hostname`"
echo "IPv4: `ifconfig |sed -n '2p' |cut -d: -f2|cut -d ' ' -f1`"
echo "System Version: `cat /etc/redhat-release`"
echo "Kernel: `uname -r`"
echo "Cpu: `lscpu |grep "name" |tr -s ' '|cut -d ' ' -f5`"
echo "Memory: `free -h|sed -n '2p'|tr -s ' '|cut -d ' ' -f2`"
echo "Hard Disk: `fdisk -l | sed -n '2p' |cut -d' ' -f3,4|cut -d',' -f1`"
 
[root@centos6 tmp]# bash systeminfo.sh 
HostName: centos6
IPv4: 10.1.255.76
System Version: CentOS release 6.8 (Final)
Kernel: 2.6.32-642.el6.x86_64
Cpu: i7-4810MQ
Memory: 1.8G
Hard Disk: 214.7 GB
[root@centos6 tmp]#

2、编写脚本/root/bin/backup.sh,可实现每日将/etc/目录备份到/root/etcYYYY-mm-dd中

[root@centos6 tmp]# cat backup.sh 
#!/bin/bash
#

cp -r /etc/ /root/etc-`date +%F`
[root@centos6 tmp]# crontab -l
0 23 */1 * * /bin/bash /tmp/backup.sh
[root@centos6 tmp]#

3、编写脚本/root/bin/disk.sh,显示当前硬盘分区中空间利用率最大的值

[root@centos6 tmp]# cat disk.sh 
#!/bin/bash
#

echo "Hard disk sda is space utilization: `df -h |grep 'sda*' | tr -s ' '|cut -d' ' -f5 |sort -n | cut -d'%' -f1 |tail -1`"
[root@centos6 tmp]# bash disk.sh 
Hard disk sda is space utilization: 22
[root@centos6 tmp]#

4、编写脚本/root/bin/links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排序

[root@centos6 tmp]# cat link.sh 
#!/bin/bash
#

echo -e "远程主机连接统计为:\n\t连接数\t远程主机IP"
netstat -nt | tr -s ' ' | cut -d' ' -f5 | tr -cs '0-9.' '\n' | egrep '([0-9]+.){3}[0-9]+' | sort | uniq -c | sort -nr | tr -s ' ' '\t'
[root@centos6 tmp]# bash link.sh 
远程主机连接统计为:
	连接数	远程主机IP
	2	10.1.250.48
[root@centos6 tmp]#

5、写一个脚本/root/bin/sumid.sh,计算/etc/passwd文件中的第10个用户和第20用户的ID之和

[root@centos6 tmp]# 
[root@centos6 tmp]# cat sumid.sh 
#!/bin/bash
#

Link1=`sed -n '10p' /etc/passwd |cut -d: -f3`
Link2=`sed -n '20p' /etc/passwd |cut -d: -f3`

echo "第10个用户和第20用户的ID之和: $((Link1+Link2))"
[root@centos6 tmp]# bash sumid.sh 
第10个用户和第20用户的ID之和: 180
[root@centos6 tmp]#

6.1、写一个脚本/root/bin/sumspace.sh,传递两个文件路径作为参数给脚本,计算这两个文件中所有空白行之和

[root@centos6 tmp]# cat sumspace.sh 
#!/bin/bash
#

Spacetotal1=`grep '^$' $1 |wc -l`
Spacetotal2=`grep '^$' $2 |wc -l`

echo "$1和$2空白行之和为: $((Spacetotal1+Spacetotal2))"

[root@centos6 tmp]# bash sumspace.sh /etc/fstab /etc/issue
/etc/fstab和/etc/issue空白行之和为: 2
[root@centos6 tmp]#

6.2、写一个脚本/root/bin/sumfile.sh,统计/etc, /var, /usr目录中共有多少个一级子目录和文件

[root@centos6 tmp]# 
[root@centos6 tmp]# cat sumfile.sh 
#!/bin/bash
#

Etctotal=`ls -a /etc |wc -l`
Vartotal=`ls -a /var |wc -l`
Usrtotal=`ls -a /usr |wc -l`


echo "Sumfiletotal: $((Etctotal+Vartotal+Usrtotal))"
[root@centos6 tmp]# bash sumfile.sh 
Sumfiletotal: 292
[root@centos6 tmp]#

7、写一个脚本/root/bin/argsnum.sh,接受一个文件路径作为参数;如果参数个数小于1,则提示用户“至少应该给一个参数”,并立即退出;如果参数个数不小于1,则显示第一个参数所指向的文件中的空白行数

[root@centos6 tmp]# 
[root@centos6 tmp]# cat argsnum.sh 
#!/bin/bash
#

[ $# -lt 1 ] && echo "At least to a argument" || grep '^$' $1|wc -l 
[root@centos6 tmp]# bash argsnum.sh 
At least to a argument
[root@centos6 tmp]# bash argsnum.sh /etc/fstab 
1
[root@centos6 tmp]#

8、写一个脚本/root/bin/hostping.sh,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping通,则提示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”

[root@centos6 tmp]# cat hostping.sh 
#!/bin/bash
#

ping -c1 -W1 $1 &>/dev/null && echo "The $1 address can access." || echo "The $1 address can not access."
[root@centos6 tmp]# bash hostping.sh 10.1.0.1
The 10.1.0.1 address can access.
[root@centos6 tmp]# bash hostping.sh 10.1.0.0
The 10.1.0.0 address can not access.
[root@centos6 tmp]#

9、chmod -rw /tmp/file1,编写脚本/root/bin/per.sh,判断当前用户对/tmp/fiile1文件是否不可读且不可写

[root@centos6 tmp]# su - wang
[wang@centos6 ~]$ ls -l /tmp/file1
----------. 1 root root 1 Aug  7 10:30 /tmp/file1
[wang@centos6 ~]$ cat /tmp/per.sh
#!/bin/bash
#

[ -r /tmp/file1 -a -w /tmp/file1 ] && echo "`whoami` can  wrint and read" || echo "`whoami` can not wrint and read"
[wang@centos6 ~]$ bash /tmp/per.sh
wang can not wrint and read
[wang@centos6 ~]$

10、编写脚本/root/bin/nologin.sh和login.sh,实现禁止和充许普通用户登录系统。

[root@centos6 tmp]# cat login.sh 
#/bin/bash
#

[ -f /etc/nologin ] && (rm -f /etc/nologin;echo user enable login) || echo user disable login already
[root@centos6 tmp]# bash login.sh 
user disable login already

11、写一个脚本/root/bin/hostping.sh,接受一个主机的IPv4地址做为参数,先判断是否合格IP,否,提示IP格式不合法并退出,是,测试是否可连通。如果能ping通,则提示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”。(只提供源码,不测试)

[root@centos6 tmp]# cat hostping.sh 
#!/bin/bash
#

echo "$1" | egrep '\<([1-9]|[1-9][0-9]|1[0-9]{2}|2[01][0-9]|22[0-3])\>(\.\<([0-9]|[0-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>){2}\.\<([1-9]|[0-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-4])\>' &> /dev/null

if [ $? -eq 0 ];then
     echo "This $1 is qualified ipv4."
     ping -c1 -W5 $1 &>/dev/null && echo "The $1 address can access." || echo "The $1 address can not access."
  else
     echo "This $1 is not qualified ipv4." 
fi

12、计算1+2+3+…+100的值

[root@centos6 tmp]# cat addnum.sh 
#!/bin/bash
#

declare -i sum=0
declare -i i=1

read -p "Enter in a positive integer:"  Number

while [ $i -le $Number ]; do
let sum+=$i
let i++
done

echo "Summary: $sum."
[root@centos6 tmp]# bash addnum.sh 
Enter in a positive integer:100
Summary: 5050.
[root@centos6 tmp]#

13、计算从脚本第一参数A开始,到第二个参数B的所有数字的总和,判断B是否大于A,否提示错误并退出,是则计算之。(只提供源码,不测试)

[root@centos6 tmp]# cat last.sh
#!/bin/bash
#

read -p "please input first number:" First
read -p "please input second number:" Second

if [ $First -ge $Second ]; then
        echo "$First greater than $Second,calculation error." && exit 1
  else
        for i in `seq $First $Second`; do
             let sum+=$i
             let i++
        done
        echo "Summary: $sum."
fi

[root@centos6 tmp]#

原创文章,作者:Aleen,如若转载,请注明出处:http://www.178linux.com/33534

(0)
AleenAleen
上一篇 2016-08-13 21:01
下一篇 2016-08-14 17:44

相关推荐

  • 根DNS域名解析的实现

    一、实现从根,com,rj.com 模拟互联网的DNS架构 DNS(Domain Name System,域名系统),因特网上作为域名和IP地址相互映射的一个分布式数据库,能够使用户更方便的访问互联网,而不用去记住能够被机器直接读取的IP数串。 接下来就一起开始搭建吧 首先,我们需要计划好实验环境,包括实验的步骤思路 1)实验环境(最好是画图展示,能使思路清…

    2015-02-10
  • 互联网安全之iptables/netfilter入门到进阶

    随着互联网技术的方兴未艾,各种网络应用层出不穷,网络攻击、黑客入侵也成了网民畅游互联网的心头大患,互联网安全也愈加受到了人们的重视。网络防火墙,作为一种简单高效的互联网防御手段,逐渐成为了网民畅游网络世界的保护伞。下面笔者介绍下Linux系统的守卫者——iptables/netfilter。  一 兄弟齐心,其利断金  iptables/netfilter就…

    Linux干货 2017-05-06
  • OpenSSL

    OpenSSL由三部分组成:             libencrypto库             libssl库 …

    Linux干货 2017-05-30
  • liunx性能监控工具总结

    1.uptime 1)显示的信息:显示当前时间,系统已启动的时间,当前在线人数,系统平均负载(1分钟、5分钟、10分钟的平均负载,一般不会超过1) 2)系统平均负载:指在特定时间间隔内运行队列中的平均进程数。 3)如果每个CPU内核的当前活动进程数不大于3的话,那么系统的性能良好。如果每个CPU内核的任务数大于5,那么这台及其的性能有严重问题 4)ruguo…

    Linux干货 2016-09-09
  • Redis的编译安装

    介绍     redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更…

    Linux干货 2015-02-28
  • 程序包管理初步

    升级:       rpm {-U|–upgrade} [install-options] PACKAGE_FILE …                -U:升级或安装;       rpm {-…

    Linux干货 2016-12-31

评论列表(1条)

  • 马哥教育
    马哥教育 2016-08-16 17:22

    文章结构层次清晰,内容充实,有理论有操作,排版也很用心,希望能坚持下去,写出更好的博客。