Linux Shell编程——变量

一、变量的定义

变量即在程序运行过程中他的值是允许改变的量
变量是用一串固定的字符来表示不固定的值的一种方法
变量是一种使用方便的占位符,用于引用计算机内存地址,该地址可以存储 Script 运行的时可更改的程序信息
在 Shell 中变量是不可能永久保存在系统中的,必须在文件中声明

二、Shell 脚本中变量的种类

1.环境级变量

只在当前的shell种生效,shell 关闭则变量丢失

定义方法:
export A=1

2.用户级变量

写在用户的骨文件中,只针对当前用户生效

定义方法:

vim ~/.bash_profile
export A=1

3.系统级变量

系统级变量被写在系统的配置文件 /etc/profile或者 /etc/profile.d/ 中,对所有的用户都生效

定义方法:

vim /etc/profile
export A=1

或者cd /etc/profile.d/

vim westos.sh
#!/bin/bash
export A=1

注意:用户级与系统级的编辑之后要source

三、变量名称的规范

变量名称中通常包含大小写字母,数字,下划线(不是必须的)
变量名称的格式
WESTOS_LINUX
Westos_Linux
westoS_Linux

四、字符的转译以及变量的声明

\ 转译单个字符
"" 弱引用,批量转译 " " 中出现的字符
'' 强引用,批量转译 ’ ’ 中出现的字符(原样输出)
''""的区别:"" 不能转译"\""反向单引号""!""$""?"
${} 变量的声明

五、变量值的传递

$1 脚本后的第1串字符串
$2 脚本后的第2串字符串
$0 获取shell脚本文件名,如果执行时包含脚本路径,则输出脚本路径
$# 脚本后所跟字符串的个数
$* 脚本后跟的所有字符串,模式为"1 2 3"
$@ 脚本后跟的所有字符串,模式为 " 1 " " 2 " " 3 "
$? 是命令在执行完成后产生的退出值;范围[0-255],为0表示没有错误输出(exit可以设置退出值)
$$ 获取当前shell的进程号

六、用read实现变量传递

[root@shellexample mnt]# read westos
westos hello
[root@shellexample mnt]# echo $westos
westos hello
[root@shellexample mnt]# read -p "input:" i
input:10
[root@shellexample mnt]# echo $i
10

七、Linux 系统中命令别名的设置

alias xie='vim'
vim ~/.bashrc
alias xie='vim'
vim /etc/bashrc
alias xie='vim'
unalias xie

扩充:
``$( ) 的区别

[root@shellexample mnt]# export a=`hostname`
[root@shellexample mnt]# echo $a
shellexample.westos.com
[root@shellexample mnt]# export a=$(hostname)
[root@shellexample mnt]# echo $a
shellexample.westos.com

反向单引号是通用的; $( )不通用
yum install perl

[root@shellexample mnt]# vim test1
#!/usr/bin/perl
print `date`
[root@shellexample mnt]# chmod +x test1
[root@shellexample mnt]# /mnt/test1
Thu Mar  7 01:17:26 EST 2019
[root@shellexample mnt]# vim test2
#!/usr/bin/perl
print $(date)
[root@shellexample mnt]# chmod +x test2
[root@shellexample mnt]# /mnt/test2
Bareword found where operator expected at /mnt/test2 line 2, near "$(date"
	(Missing operator before date?)
syntax error at /mnt/test2 line 2, near "date)
"
Execution of /mnt/test2 aborted due to compilation errors.

猜你喜欢

转载自blog.csdn.net/weixin_44209804/article/details/88294657