Shell编程-shell变量1

10 篇文章 0 订阅
1.shell变量:
变量:是shell传递数据的一种方式,用来代表每个取值的符号名

2.shell变量设置规则
不能以数字开头
变量默认都是字符串类型
[root@VM_0_16_centos es]# num3=$num+$num2
[root@VM_0_16_centos es]# echo $num3
12+13

如果变量有空格,需要使用单双引号
[root@VM_0_16_centos es]# pro=pro fillll
-bash: fillll: command not found
[root@VM_0_16_centos es]# pro="pro fillll"
[root@VM_0_16_centos es]#


=号两边不能有空格
[root@VM_0_16_centos es]# lxx = 1
-bash: lxx: command not found
[root@VM_0_16_centos es]# lxx =1
-bash: lxx: command not found


3.分类
用户自定义变量
环境变量 $HOME,$SHELL,$PWD,$USER等
位置参数变量
预定义变量

使用set查看系统中所有的变量







1)用户自定义变量
[root@VM_0_16_centos es]# num2=123
[root@VM_0_16_centos es]# num3=234



2)变量调用,使用$xxxName 调用变量的值

3)将一个变量赋值给另一个变量

4)将运算的结果赋值给变量
[root@VM_0_16_centos es]# num4=`ll`
[root@VM_0_16_centos es]# echo $num4
total 28 -rwxr-xr-x 1 root root 18 May 10 14:44 firstshell -rw-r--r-- 1 es root 136 May 9 09:28 hello2.txt.tar.gz -rwxrwxrwx 1 es es 156 May 9 12:38 hello.txt -rw-rw-r-- 1 es es 136May 8 19:21 hello.txt.tar.gz -rw-rw-r-- 1 es es 182 May 8 19:12 hello.txt.zip drwxr-xr-x 2es es 4096 May 9 09:32 temp drwxr-xr-x 2 root root 4096 May 8 19:10 tody

使用$()
[root@VM_0_16_centos home]# num5=$(ll /home/es)
[root@VM_0_16_centos home]# echo $num5
total 28 -rwxr-xr-x 1 root root 18 May 10 14:44 firstshell -rw-r--r-- 1 es root 136 May 9 09:28 hello2.txt.tar.gz -rwxrwxrwx 1 es es 156 May 9 12:38 hello.txt -rw-rw-r-- 1 es es 136May 8 19:21 hello.txt.tar.gz -rw-rw-r-- 1 es es 182 May 8 19:12 hello.txt.zip drwxr-xr-x 2es es 4096 May 9 09:32 temp drwxr-xr-x 2 root root 4096 May 8 19:10 tody
[root@VM_0_16_centos home]#


[root@VM_0_16_centos home]# num6=$((4+5))
[root@VM_0_16_centos home]# echo $num6
9
[root@VM_0_16_centos home]#


拼接
[root@VM_0_16_centos home]# str1=123.123.123
[root@VM_0_16_centos home]# str2=root@$str1
[root@VM_0_16_centos home]# echo $str2
root@123.123.123
[root@VM_0_16_centos home]# str3=root@${str1}
[root@VM_0_16_centos home]# echo $str3
root@123.123.123
[root@VM_0_16_centos home]# str4=root@"$str1"
[root@VM_0_16_centos home]# echo str4
str4[root@VM_0_16_centos home]# echo $str4root@123.123.123[root@VM_0_16_centos home]#



转义使用''单引号
[root@VM_0_16_centos home]# str5=root@'$str1'
[root@VM_0_16_centos home]# echo $str5
root@$str1
[root@VM_0_16_centos home]#


列出所有的变量
set命令



删除变量
unset

但是,有一种变量无法使用unset删除
readonly变量:
[root@VM_0_16_centos home]# readonly rnum=123
[root@VM_0_16_centos home]# unset rnum
-bash: unset: rnum: cannot unset: readonly variable
[root@VM_0_16_centos home]#



用户自定义的变量,作用域只在当前的shell中,如果重启那么就失效。













环境变量


作用域:当前shell及子shell





使用bash进入一个新的bash环境
使用exit退出当前的bash

执行bash firstshell时,会进入一个bash,执行完毕后并退出bash,我们可能看不到bash,因为执行的速度太快,我们可以在bash中执行sleep 5睡眠5s。














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值