SHELL—变量

一.普通变量

定义变量示例:

[root@server ~]# a=hello
[root@server ~]# echo $a
hello
[root@server ~]# b='hello'
[root@server ~]# echo $b
hello
[root@server ~]# c="hello"
[root@server ~]# echo $c
hello
[root@server ~]# a=westos-$a
[root@server ~]# echo $a
westos-hello
[root@server ~]# b='westos-$a'
[root@server ~]# echo $b
westos-$a
[root@server ~]# c="westos-$a"
[root@server ~]# echo $c
westos-westos-hello
[root@server ~]# a=westos hello
bash: hello: command not found...
[root@server ~]# a="westos hello"
[root@server ~]# echo $a
westos hello

注意:

建议没有特别要求时,字符串都加双引号,需要原样输出就加单引号

二.特殊变量

$0:获取脚本文件名,如果执行时包含路径,则输出脚本路径
$n(>0):获取脚本的第n个参数
$#:获取脚本后参数的总个数
$*:获取所有参数
$@:
$?:表示上条命令执行结果的返回值,0表示执行成功,非0表示执行失败
$$:获取当前shell进程号
  • $0
[root@server mnt]# cat westos.sh 
#!/bin/bash
echo $0
[root@server mnt]# sh westos.sh 
westos.sh
[root@server mnt]# /mnt/westos.sh 
/mnt/westos.sh
  • $n
[root@server mnt]# cat westos.sh 
#!/bin/bash
echo $1 $2

[root@server mnt]# sh westos.sh hello westos
hello westos
[root@server mnt]# sh westos.sh hello redhat
hello redhat

[root@server mnt]# echo \${1..10} > westos.sh 
[root@server mnt]# cat westos.sh 
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10
[root@server mnt]# sh westos.sh  {1..10}
1 2 3 4 5 6 7 8 9 10
[root@server mnt]# sh westos.sh  {a..z}
a b c d e f g h i a0
[root@server mnt]# sh westos.sh  {a..z}
a b c d e f g h i j
  • $#
$#:
[root@server mnt]# cat westos.sh ]
echo $1 $2 $3 $4 $5 $6 $7 $8 $9
echo $#
[root@server mnt]# sh westos.sh {1..100}
1 2 3 4 5 6 7 8 9
100
  • $?
[root@localhost mnt]# ls /etc/passwd
/etc/passwd
[root@localhost mnt]# echo $?
0
[root@localhost mnt]# ls /etc/passsswd
ls: cannot access /etc/passsswd: No such file or directory
[root@localhost mnt]# echo $?
2
[root@localhost mnt]# 
  • $$
[root@localhost mnt]# echo $$
1624
[root@localhost mnt]# ps
  PID TTY          TIME CMD
 1624 pts/0    00:00:00 bash
 2135 pts/0    00:00:00 ps

三.read命令

[root@server mnt]# read str
westos hello
[root@server mnt]# echo $str
westos hello
[root@server mnt]# read -p "请输入一个整数:" i
请输入一个整数:10

四.将命令的结果赋值给变量

[root@server mnt]# CMD=`ls -l`
[root@server mnt]# echo $CMD
total 8 -rwxr-xr-x. 1 root root 492 Dec 22 10:25 test.sh -rwxr-xr-x. 1 root root 40 Dec 22 10:40 westos.sh

[root@server mnt]# CMD=$(ls -l)
[root@server mnt]# echo $CMD
total 8 -rwxr-xr-x. 1 root root 492 Dec 22 10:25 test.sh -rwxr-xr-x. 1 root root 40 Dec 22 10:40 westos.sh

五.练习

  • 打包日志
[root@server mnt]# tar zcf log_$(date +%F).tar.gz /var/log/
tar: Removing leading `/' from member names
[root@server mnt]# ls
log_2018-12-22.tar.gz  test.sh  westos.sh

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值