文章目录
一、变量的定义
#定义本身
变量就是内存一片区域的地址
#变量存在的意义
命令无法操作一直变化的目标
用一串固定的字符来表示不固定的目标可以解决此问题
二、shell脚本中变量的定义方法
注意:不同进程之间是不能共享资源的,一个进程中的线程可以使用该进程的资源
1.环境级别
2.用户级别
3.系统级别
影响范围越小,优先等级越高
#### 环境级别
export a=1
在环境关闭后变量失效
#### 用户级别
vim ~/.bash_profile
export a=1
#### 系统级别
vim /etc/profile ##与下面文件效
export a=2
vim /etc/profile.d/westos.sh ##建议编辑此文件
export b=3
source /etc/profile.d/westos.sh ##使用此命令进行刷新
系统默认读取的文件顺序为
全局设定----->用户设定,需重新source才可以使用全局设定
4.变量名称
#### 变量名称可包含的字符
字母
下划线_
数字
#### 变量名称定义规则
不能用数字开头
#### 建议:
变量名称短全用大写字符
变量名称长用_区分子类
WESTOS ##全部大写
Westos_Linux ##波型
westoS_Linux ##峰型
三、变量的转译
#1)转译
\ #转译单个字符
" " #弱引用,批量转译个数字符 不能转译"\ " "" "$" "!"
' ' #强引用
#2)声明
a=1
echo $ab
echo ${a}b
#3)变量的数组
a=(1 2 3 4 5)
a$[a[@]:起始元素id:元素个数]
echo ${a[0]} ##数组中第一个元素
echo ${a[-1]} ##数组中最后一个元素
echo ${a[*]} ##数组中所有元素;*将12345视为一个整体
echo ${a[@]} ##数组中所有元素;@将12345视为5个数
echo ${a[@]:0:3} ##数组中1-3元素
echo ${#a[@]} ##数组中元素的个数
a[6] =8 ##添加第6个元素值为8
unset a[n] ##删除数组中的第n1个元素
unset a ##删除a这个数组
四、Linux中命令的别名设定
1.临时设定
2.用户级别
3.系统级别
alias xie='vim' ##临时设定
vim ~/.bashrc
alias xie='vim' ##只针对与用户生效
vim /etc/bashrc ##针对系统所以用户生效
alias xie='vim'
unalias xie ##删除当前环境中的alias;删除文件内修改后执行即可
五、用户环境变量的更改
环境变量:用户在操作系统时使用到的命令搜索路径
1.用户级别
2.系统级别
vim ~/.bash_profile ##用户级别
export PATH=$PATH:/mnt
vim /etc/bash_profile ##系统级别:也可执行/etc/profile.d/path.sh中建立
export PATH=$PATH:/mnt
用户级别:
系统级别:
六、利用命令的执行结果设定变量
#1)直接利用命令执行结果
$ () | "" ##这四种优先执行
TEST=hostname TEST=$(hostname)
#2)脚本中的传参
非交互模式:
$0 is /mnt/test.sh <!脚本本身>
$1 is westos <!脚本后所输入的第一串字符>
$2 is linux
$3 is redhat
$* is westos linux redhat <!脚本后所输入的所有字符"westos linux redhat">
$@ is westos linux redhat <!脚本后所输入的所有字符'westos' 'linux' 'redhat'>
$# is 3 <!脚本后所输入的字符串个数>
交互模式传参:
read WESTOS ##对westos赋值
read p "please input word:" ##输出提示语
-s ##隐藏输入内容
非交互式传参:
[root@westos_student50 mnt]# vim test.sh
[root@westos_student50 mnt]# cat test.sh
###############################################
#!/bin/bash
echo '$0' is $0
echo '$1' is $1
echo '$2' is $2
echo '$3' is $3
echo '$#' is $#
echo '$*' is $*
echo '$@' is $@
[root@westos_student50 mnt]# sh test.sh
$0 is test.sh
$1 is
$2 is
$3 is
$# is 0
$* is
$@ is
[root@westos_student50 mnt]# sh test.sh westos
$0 is test.sh
$1 is westos
$2 is
$3 is
$# is 1
$* is westos
$@ is westos
[root@westos_student50 mnt]# sh test.sh westos hello
$0 is test.sh
$1 is westos
$2 is hello
$3 is
$# is 2
$* is westos hello
$@ is westos hello
[root@westos_student50 mnt]# sh test.sh westos hello world
$0 is test.sh
$1 is westos
$2 is hello
$3 is world
$# is 3
$* is westos hello world
$@ is westos hello world
七、脚本函数
脚本中的脚本就叫函数,变量是对于一串字符进行赋值,函数是把一个动作或一个动作组合赋值
定义:
程序的别名
设定方式:
WORD()
{
action1
action2
}
WORD 在脚本中就代表action1 action2这两个动作