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

相关文章
|
5天前
|
存储 Shell Linux
八、Linux Shell 脚本:变量与字符串
Shell脚本里的变量就像一个个贴着标签的“箱子”。装东西(赋值)时,=两边千万不能有空格。用单引号''装进去的东西会原封不动,用双引号""则会让里面的$变量先“变身”再装箱。默认箱子只能在当前“房间”(Shell进程)用,想让隔壁房间(子进程)也能看到,就得给箱子盖个export的“出口”戳。此外,Shell还自带了$?(上条命令的成绩单)和$1(别人递进来的第一个包裹)等许多特殊箱子,非常有用。
56 2
|
7月前
|
关系型数据库 MySQL Shell
MySQL 备份 Shell 脚本:支持远程同步与阿里云 OSS 备份
一款自动化 MySQL 备份 Shell 脚本,支持本地存储、远程服务器同步(SSH+rsync)、阿里云 OSS 备份,并自动清理过期备份。适用于数据库管理员和开发者,帮助确保数据安全。
|
5月前
|
存储 Unix Shell
确定Shell脚本在操作系统中的具体位置方法。
这对于掌握Linux的文件系统组织结构和路径方面的理解很有帮助,是我们日常工作和学习中都可能使用到的知识。以上讲解详细清晰,应用简便,是每一个想要精通操作系统的计算机爱好者必备的实用技能。
105 17
|
5月前
|
Linux Shell
Centos或Linux编写一键式Shell脚本删除用户、组指导手册
Centos或Linux编写一键式Shell脚本删除用户、组指导手册
126 4
|
5月前
|
Linux Shell 数据安全/隐私保护
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
270 3
|
6月前
|
Linux Shell
在Linux、CentOS7中设置shell脚本开机自启动服务
以上就是在CentOS 7中设置shell脚本开机自启动服务的全部步骤。希望这个指南能帮助你更好地管理你的Linux系统。
433 25
|
7月前
|
关系型数据库 Shell 网络安全
定期备份数据库:基于 Shell 脚本的自动化方案
本篇文章分享一个简单的 Shell 脚本,用于定期备份 MySQL 数据库,并自动将备份传输到远程服务器,帮助防止数据丢失。
|
网络协议 Shell Linux
【Linux】shell编程基础(超详细,入门看这一篇就够了)(下)
【Linux】shell编程基础(超详细,入门看这一篇就够了)(下)
164 0
|
Java Shell Linux
【Linux】shell编程基础(超详细,入门看这一篇就够了)(上)
【Linux】shell编程基础(超详细,入门看这一篇就够了)
1101 0
|
存储 Shell C语言
shell脚本 编程 变量 基本入门(详解)
shell脚本 编程 变量 基本入门(详解)
217 1