shell脚本编程及位置变量详解|学习笔记

简介: 快速学习shell脚本编程及位置变量详解

开发者学堂课程【Linux Shell 编程入门与实战shell脚本编程及位置变量详解】学习笔记,与课程紧密联系,让用户快速学习知识。

课程链接:https://developer.aliyun.com/learning/course/551/detail/7622?



内容介绍:

一、 局部变量和全局变量

二、 环境变量

三、 只读和位置变量


一、局部变量和全局变量

(1)局部变量

变量赋值:name='value'

可以使用引用value:

(1)可以是直接字串;name=“root”

(2)变量引用:name="$USER"

(3)命令引用:name=`coMMAND`name=s(coMMAND)

变量引用:${name}  $name

"":弱引用,其中的变量引用会被替换为变量值

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

显示已定义的所有变量:set

删除变量:unset name

变量的使用

变量:系统自带的变量和自定义的变量

(2)练习

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

答:显示主机名:[rooot@centos7 ~]#hostname

显示IP地址:(以为ens33网址例):[rooot@centos7 ~]#ifconfig ens33

操作系统版本:[rooot@centos7 ~]#cat /etc/centos-release

内核版本:[rooot@centos7 ~]#uname  -r

CPU型号:[rooot@centos7 ~]#lscpu

内存大小:[rooot@centos7 ~]#free -h 或[rooot@centos7 ~]#cat /proc/meminfo

硬盘大小:[rooot@centos7 ~]#lsblk |grep “^sd”

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

答:

[rooot@centos7 ~]#vim backuo.sh

echo -e  “Start backup...”

sleep 2

cp -av /etc/ /root/etc “date +%F”

echo “Backup is finished”

“backup.sh” [New] 15L,435C written

[rooot@centos7 ~]#chomed +x backup.sh

[rooot@centos7 ~]#ls /root

[rooot@centos7 ~]#ls /data

[rooot@centos7 ~]#vim backup.sh

[rooot@centos7 ~]#vim backuo.sh

echo -e  “\e[1;31mStart backup...\e[0m”

sleep 2

cp -av /etc/ /root/etc “date +%F”

echo -e “\e[1;31m Backup is finished \e[0m”

“backup.sh” [New] 15L,435C written

[rooot@centos7 ~]#backup.sh

Start backup...

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

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


二、环境变量

(1)环境变量

变量声明、赋值:

export name=VALUE

declare-x name=VALUE

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

显示所有环境变量:

env

printenv

export

declare -x

删除变量:

unset name

bash内建的环境变量:

PATH

SHELL

USER

UID

HOME

PWD

SHLVL

LANG

MAIL

HOSTNAME

HISTSIZE

(2)部分介绍:

1.SHLVL

[rooot@centos7 ~]#echo $name

wang

[rooot@centos7 ~]#echo ${name}

wang

[rooot@centos7 ~]#echo $SHLVL

2

[rooot@centos7 ~]#bash

[rooot@centos7 ~]#echo $SHLVL

3

[rooot@centos7 ~]#bash

[rooot@centos7 ~]#echo $SHLVL.

4.

[rooot@centos7 ~]#exit

exit

[rooot@centos7 ~]#echo $SHLVL

3

[rooot@centos7 ~]#exit

exit

[rooot@centos7 ~]#echo $SHLVL

2

[rooot@centos7 ~]#exit

exit

[rooot@centos7 ~]#echo $SHLVL

1

2._

[rooot@centos7 ~]#echo $_

1

[rooot@centos7 ~]#echo a b c

a b c

 [rooot@centos7 ~]#echo $_

 c

 [rooot@centos7 ~]#ls /boot  /data  /root

 [rooot@centos7 ~]#echo $_

 /root


三、只读和位置变量


1):只读变量

只读变量:只能声明,但不能修改和删除

声明只读变量:

readonly name

declare -r name

查看只读变量:

readonly -p

(2)位置变量

位置变量:在湖本代码中调用通过命令行传递给脚本的参数$1,$2,....对应第1、第2等参数,shift[n]换位置

$0:命令本身

$*:传递给脚本的所有参数,全部参数合为一个字符串

$@:传递给脚本的所有参数,每个参数为独立字符串

$#:传递给脚本的参数的个数

$@$*只在被双引号包起来的时候才会有差异

set--清空所有位置变量

(3)详细理解

1.readonly

[root@centos7 ~]#readonly name=mage[root@centos7 ~]#echo $nameMage[root@centos7 ~]#name =wang-bash: name : readonly variable[root@centos7 ~]#unset name-bash: unset : name :cannot unset: readonly variable[root@centos7 ~]#set |grep name_=namename=mage COMPREPLY=($(compgen-A hostname -- $cur _word));compopt -o  fillenames ;compopt -o  fillenames ;COMPREPLY=($(compgen -o dirnames -- ${cur}))--skip-symlinks--changelog-limit--unique-md-filenames--simple-md-filenames --retain-old-md --distro-content-repo--unique-md-filenames--simple-md-filenames'--"$2"));compost -o filenames 2> /dev/null;compost -o fillentness;COMPREPLY+=($(compgen -A hostname -P "$prefix$user" -S "$suffix"-"$cur"));_pnames()Localcollections=($(find/tec/sel/prefixes -madeupth)-middopth 1-type f-exec  basename {}\;| sort -u))scriptlets+="($(find $prefix/$col/* -maxdeph 1-type f-exec basename{}\;|sort=-u));[[$result -gt 0]]&& compopt -o filenames 2>/dev/null;Echo “${FUNCAME[0]}:usage:${FUNCNAME[0]} [-v varname” “value]|[-aN varname [value...]]…" 1>&2;local userland=$(uname -s);COMPREPLY=($(compgen -W 'name summary  description ‘ -- "$cur"));COMPREPLY=($( company -W 'get set del rename rename -force copy search-R|--randomwait|-x|--exclude|-h|--help|--version|--releasever|--cve|--bz|--advisory|--tmprepo|--verify-filenams 1 |--setopt)for db in $(find  "$YUM_CACHEDIR" -name primary_ db. sqlite);COMPREPLY+=($(sqlite3 "$db"    "SELECT name||'.'||arch FROM packages WHERE name LIKE"S31%"

2.declare -r

当退出程序对应的结果也会消失,程序结束对应的变量也会消失,变量的生命有效期就是程序运行的时期,程序什么时候结束常量就会结束。

常量的运用不多但还是要用到的比如Π,有时候回去到3.14,有时候是3.1415,常量主要是要保证他的固定值。

[root@centos7 ~]#pi=3.14

显示常量

[root@centos7 ~]#declare -r

3.部分技巧

a.()  如果不加,影响的是当前的事,命令结束后不保留影响但会把所包含的内容共同执行

例如:

[root@centos7 ~]#umask 026; touch / data/f1[root@centos7 ~]#11 / data/f1-rw-r-----. 1 root root 0 Apr 9 19:10 /data/f1[root@centos7 ~]#tpuch /data/f2[root@centos7 ~]#11 /data/f2-rw-r-----. 1 root root 0 Apr 9 19:10 /data/f2[root@centos7 ~]#umask 0026

现在创造一个文件,是实现000的权限后续创建的文件默认不改

[root@centos7 ~]#rm -rf /data/*[root@centos7 ~]#(umask 666;touch /data/f1)[root@centos7 ~]#11 /data/f1----------.  1 root 0 apr 9 19:11 /data/f1[root@centos7 ~]#umask0022[root@centos7 ~]#( cd /data/ rm -rf /data/*)[root@centos7 ~]#ls /data[root@centos7 ~]#( name=wang;echo $name )[root@centos7 ~]#echo $name[root@centos7 ~]#man bash

b.{}只影响当前环境下的,但会把所包含的内容共同执行

[root@centos7 ~]#{ name =mage;echo $name; }mage[root@centos7 ~]# echo $namemage[root@centos7 ~]#( name =mage;echo $name; )haha[root@centos7 ~]# echo $namemage

(4)练习:

[root@centos7 ~]#x=1; echo “pid =$$”;(echo “subpid=$$”;echo   “subx=$x”;x=2;echo “subx2 =$x”);echo x=$x

运行结果:

pid=2887

subpid =2887

subx=1

subx2=2

x=1

位置变量——让脚本写的更加灵活

目前的学习中,脚本的功能是死板的,不能变化比如说:

[root@centos7 ~]# backup.sh

但在Linux系统中有许多变化的命令比如说:

[root@centos7 ~bin]# ls

backup.sh f1.sh

[root@centos7 ~bin]# ls -l

total 8

-rwxr-xr-x. 1 root root 467 Apr 9 19:01 backup.sh

-rwxr-xr-x. 1 root root 396 Apr 9 17:40 f1.sh

[root@centos7 ~bin]# ls -a

backup.sh f1.sh

在脚本后面加上不同的东西实现不同的功能就可以使脚本功能更加强大,这功能的实现就要用到位置变量

对于Linux来说,系统中自带了一些位置变量

//$1对应所存的第一个字符,$2对应第二个

[root@centos7 ~bin]#$1 $2 ^c

[root@centos7 ~bin]#backup.sh a b c^c

编写一个脚本

echo “1st arg is $1”

echo “2st arg is $2”

echo “3st arg is $3”

echo “All arg are $*”

echo ”All arg are $@”

echo “The args number is $#”

echo “The scripet name is $0”

“arg.sh” [New] 19L,510c written

[root@centos7 ~bin]#chmod +x arg.sh

[root@centos7 ~bin]#arg.sh xxx yy zzzz

1st arg is xxx

2st arg is yy

3st arg is zzzz

All arg are xxx yy zzzz

All arg are xxx yy zzzz

The args number is 3

The scripet name is /root/bin/arg.sh

[root@centos7 ~bin]#cat arg.sh

echo “1st arg is $1”

echo “2st arg is $2”

echo “3st arg is $3”

echo “All arg are $*”

echo ”All arg are $@”

echo “The args number is $#”

echo “The scripet name is $0”

//需要取消路径则将echo “The scripet name is $0”改为echo “The scripet name is basename $0”

改后的运行结果:

[root@centos7 ~bin]#arg.sh xxx yy zzzz

1st arg is xxx

2st arg is yy

3st arg is zzzz

All arg are xxx yy zzzz

All arg are xxx yy zzzz

The args number is 3

The scripet name is arg.sh

现在有多个数字的运行开始:

echo “1st arg is $1”

echo “2st arg is $2”

echo “3st arg is $3”

echo “9st arg is $9”

echo “10st arg is $10”

echo “All arg are $*”

echo ”All arg are $@”

echo “The args number is $#”

echo “The scripet name is $0”

运行:

“arg.sh” 21L,565c written

[root@centos7 ~bin]#seq a  z

Invalid floating point argument:a

‘seq--help’ for more information.

[root@centos7 ~bin]#echo {a..z}

a b c d e f g h I j k l m n o p q r s t u v w x y z

[root@centos7 ~bin]#arg.sh a b c d e f g h I j k l m n o p q r s t u v w x y z

1st arg is a

2st arg is b

3st arg is c

9st arg is i

10st arg is a0

All arg are a b c d e f g h I j k l m n o p q r s t u v w x y z

All arg are a b c d e f g h I j k l m n o p q r s t u v w x y z

The args number is 26

The scripet name is arg.sh

在上述结果中发现了对于识别10时存在问题,这时候就需要用到‘{}‘来解决,即将上述代码中的echo “10st arg is $10”,改为echo “10st arg is ${10}”

当然当如果对所有变量存在是否要加’{}‘的疑虑时,为了保证稳妥,就将每一个变量都加上’{}’来解决疑惑。

位置参数就是用来解决扩展程序的功能,例如现在将一个机子上的脚本复制到另一个机子的某个目录中去,需要进行以下操作

[root@centos7 ~bin]#echo magedu | passwd –stdin wang

Changing password for user wang .

passwd:all authentication tokens updated successfully.

[root@centos7 ~bin]#

注:现在在别的机子(该机子为6)上写的脚本传到上面(该机子为7)代码中wang的加目录中

[root@centos7 ~bin]#cd ~wang

[root@centos7 ~bin]#is

[root@centos7 ~bin]#mkdir bin

[root@centos7 ~bin]#cd bin/

[root@centos7 ~bin]#pwd

/home/wang/bin

[root@centos7 ~bin]#

需要先在6机中显示IP地址,运用以下语句描写:

[root@centos6 ~]#ifconfig

ls表示远程复制

[root@centos6 ~]#ls

anaconda-ks.cfg diff.log Downloads f2 fstab2.orig install.log.syslog Pictures Templates

Desktop  Documents  f1  fstab2  install.log  Music Public Videos

将当前文件f1复制到上述7机子的IP地址的目标目录中,这个过程中还需要一个人的身份来进行连接(这里以wang为例)

[root@centos6 ~]#scp f1 wang@172.20.102.77:/home/wang/bin

The  authenticity of host '172.20.102.77(172.20.102.77)’ can't be established .

RSA key fingerprint  is 59:a6:19:20:e1:d2:f0:01:6c:de:22:7e:52:31:19:40.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently  added'172. 20. 102. 77'(RSA) to the"list of known hosts.

wang@172.20.102.77’s password:

scp: /home/wang/bin/f1:Permission denied

[root@centos6 ~]#scp f1 wang@172.20.102.77:/home/wang/bin

 wang@172.20.102.77’s password:f1

现在在7机子上的bin目录下寻找是否发 文件复制过来

[wang@centos7 ~bin]#$cd bin

[wang@centos7 ~bin]#$11

total 4

-rw-r--r--. 1 wang wang 21 Apr 9 19:35 f1

每次复制的路径都是一样的,但每次的文件是不一样的就需要一个变量来代替相同的过程,

如下

先新建一个文件夹

[root@centos6 ~]#cd bin

-bash: cd: bin: No such file or directory

[root@centos6 ~]#mkdir bin

[root@centos6 ~]#cd bin

[root@centos6 ~]#pwd

/root/bin

[root@centos6 ~]#echo $PATH

/user/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:sbin:/bin/usr/sbin:/usr/bin:/root/bin

写一个scp脚本,脚本的功能时代替每次每次复制过程中的一部分长命令

[root@centos6 ~]#vim scp.sh

#!/bin/bash

echo “start copy...”

scp $1 wang@172/20/102/77:/home/wang/bin

echo “copy is finshed”

“arg.sh” [New] 4L,98c written

[root@centos6 bin]#chmod +x scp.sh

[root@centos6 bin]#lls

-bash:lls:command not found

[root@centos6 bin]#is

scp.sh

[root@centos6 bin]#scp.sh /etc/centos-release

start copy...

wang@172.20.102.77’s password:

centos-release

copy is finshed

[root@centos6 bin]#

现在在返回到机子7上:

[wang@centos6 bin]#is

centos-release Eliang f1

对多个文件的复制:

echo “start copy...”

[wang@centos7 ~bin]#$11

total 4

-rw-r--r--. 1 wang wang 21 Apr 9 19:35 f1

每次复制的路径都是一样的,但每次的文件是不一样的就需要一个变量来代替相同的过程,

如下

先新建一个文件夹

[root@centos6 ~]#cd bin

-bash: cd: bin: No such file or directory

[root@centos6 ~]#mkdir bin

[root@centos6 ~]#cd bin

[root@centos6 ~]#pwd

/root/bin

[root@centos6 ~]#echo $PATH

/user/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:sbin:/bin/usr/sbin:/usr/bin:/root/bin

写一个scp脚本,脚本的功能时代替每次每次复制过程中的一部分长命令

[root@centos6 ~]#vim scp.sh

#!/bin/bash

echo “start copy...”

scp $1 wang@172/20/102/77:/home/wang/bin

echo “copy is finshed”

“arg.sh” [New] 4L,98c written

[root@centos6 bin]#chmod +x scp.sh

[root@centos6 bin]#lls

-bash:lls:command not found

[root@centos6 bin]#is

scp.sh

[root@centos6 bin]#scp.sh /etc/centos-release

start copy...

wang@172.20.102.77’s password:

centos-release

copy is finshed

[root@centos6 bin]#

现在在返回到机子7上:

[wang@centos6 bin]#is

centos-release Eliang f1

对多个文件的复制:

echo “start copy...”

#!/bin/bash

#

#*********************************************************

#Author:                  wangxiaochun

#QQ:                     29308620

#Date:                    2018-04-09

#FileName:              f1.sh

#URL:                    http://www.magedu.com

#Description:              The test scripet

#Copyright(C):             2018 All rights reserved

#*********************************************************

echo “f1.sh:all arg are $1“

./f2/sh

再对f1.sh来说进行改正

[root@centos7 bin]#cat f1.sh f2.sh

#!/bin/bash

#

#*********************************************************

#Author:                  wangxiaochun

#QQ:                     29308620

#Date:                    2018-04-09

#FileName:              f1.sh

#URL:                    http://www.magedu.com

#Description:              The test scripet

#Copyright(C):             2018 All rights reserved

#*********************************************************

echo “f1.sh:all arg are $*“

./f2/sh “$@”

同时在执行abc的命令:

[root@centos7 bin]#f1.sh a b c

f1.sh : all arg are a b c

f2.sh : 1st arg is a

echo “f1.sh:all arg are $*“

set --

./f2/sh “$@”

运行之后会清空:

[root@centos7 bin]#f1.sh a b c

f1.sh : all arg are a b c

f2.sh : 1st arg is

相关文章
|
2天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
23 3
|
5天前
|
运维 监控 Shell
利用Shell脚本编写局域网监控软件:实时监测主机连接情况
本文介绍了如何使用Shell脚本创建一个局域网监控工具,以实时检查主机连接状态。脚本包括扫描IP地址范围检测主机可达性及使用`netstat`监控ESTABLISHED连接。此外,还展示了如何每60秒将连接数数据自动提交到指定网站API,以便实时跟踪网络活动。这个自动化监控系统有助于提升网络安全性和故障排查效率。
24 0
|
6天前
|
监控 Shell 开发工具
Shell编程
Shell编程
|
6天前
|
Shell
Shell脚本之流程控制语句
Shell脚本之流程控制语句
|
7天前
|
JSON 运维 监控
训练shell常用脚本练习(三)
【4月更文挑战第14天】shell代码训练(三)
24 1
|
11天前
|
存储 弹性计算 Shell
ecs服务器shell常用脚本练习(十)
【4月更文挑战第11天】shell代码训练(十)
142 0
|
11天前
|
弹性计算 Shell Go
ecs服务器shell常用脚本练习(九)
【4月更文挑战第10天】shell代码训练(八)
134 0
|
15天前
|
弹性计算 Shell Linux
ecs服务器shell常用脚本练习(六)
【4月更文挑战第4天】shell代码训练(六)
108 0
|
20天前
|
弹性计算 Shell 应用服务中间件
ecs服务器shell常用脚本练习(四)
【4月更文挑战第4天】shell代码训练(四)
96 0
|
21天前
|
Shell
【shell】shell命令行放在变量中执行以及变量的常用方法
【shell】shell命令行放在变量中执行以及变量的常用方法