1、预定义变量
预定义变量 | 作用 |
$? | 最后一次执行的命令的返回状态。如果这个变量的值为,证明上一个命令正确执行;如果这个变量的值为非0(具体是哪个数,由命令自己来决定),则证明上一个命令执行不正确了。 |
$$ | 当前进程的进程号(PID) |
$! | 后台运行的最后一个进程的进程号(PID) |
示例一、预定义变量$?的作用示例
[root@localhost ~]# ls
abc cde install.log sh 公共的 视频 文档 音乐
anaconda-ks.cfg cdef install.log.syslog testfile 模板 图片 下载 桌面
[root@localhost ~]# echo $?
0
[root@localhost ~]# lsgdds
-bash: lsgdds: command not found
[root@localhost ~]# echo $?
127
[root@localhost ~]# ls jigeang
ls: 无法访问jigeang: 没有那个文件或目录
[root@localhost ~]# echo $?
2
另外,&& || 命令符号在使用时,归根接地也是判断了该预定义变量 $? ;
示例二、当前前台进程或者后台进程的进程号PID
[root@localhost ~]# echo $$
8053
[root@localhost ~]# echo $!
[root@localhost ~]#
示例三、
[root@localhost ~]# cd sh
[root@localhost sh]# ll
总用量 20
-rwxr-xr-x. 1 root root 45 12月 16 17:13 canshu1.sh
-rwxr-xr-x. 1 root root 327 12月 16 17:49 canshu4.sh
-rwxr-xr-x. 1 root root 97 12月 16 09:24 hello.sh
-rwxr-xr-x. 1 root root 114 12月 16 17:26 jiafajisuanqi.sh
-rwxr-xr-x. 1 root root 204 12月 16 17:36 shili3.sh
[root@localhost sh]# vim yudingyibianliang
#!/bin/bash
#Author:xiaoxiaozhou(E-mail:2985797679@qq.com)
echo "The current process is $$"
#输出当前进程的PID
#这个PID就是yudingyibianliang.sh这个脚本执行时,生成的PID
find /root -name hello.sh &
#使用find 命令在root目录下查找的hello.sh文件
#符号&的意思是把命令放入后台执行,工作管理我们在系统管理章节会详细介绍
echo "The last one Daemon process is $! "
~
~
~
[root@localhost sh]# ./yudingyibianliang
The current process is 8215
The last one Daemon process is 8216
[root@localhost sh]# /root/sh/hello.sh
[root@localhost sh]#
2、接收键盘输入
[root@localhost ~]# read 【选项】[变量]
选项:
-p "提示信息” :在等待read输入时,输出提示信息。
-t 秒数 :read命令会一直等待用户输入,使用此选项可以指定等待时间。
-n 字符数 :read命令之接收指定的字符数,就会执行。
-s :隐藏输入的数据,适用于机密信息的输入。
[root@localhost sh]# vim canshu6.sh
#!/bin/bash
#Author:xiaoxiaozhou (E-mail:2095797679@qq.com)
read -t 30 -p "Please input your name:" name
#提示“请输入姓名” 并等待30秒,把用户的输入保存入变量name中
echo "Name is $name"
read -s -t 30 -p "Please enter your age:" age
#年龄是隐私,所以我们用“-s" 选项隐藏输入
echo "Age is $age "
echo -e "\n"
read -n 1 -t 30 -p "Please select your gender[M/F]: " gender
#使用“ -n 1 " 选项只接收一个输入字符就会执行(都不用输入回车)
echo -e "\n"
echo "Sex is $gender "
~
~
~
[root@localhost sh]#
[root@localhost sh]# chmod 765 canshu6.sh
[root@localhost sh]# ./canshu6.sh
Please input your name:xiaoxiaozhou
Name is xiaoxiaozhou
Please enter your age:Age is 24224
Please select your gender[M/F]: F
Sex is F
[root@localhost sh]#
补充:如果在Linux中,输入内容错误,想按 退格键,需要同时按住Ctrl键才可。
如上,年龄在执行时,因为脚本中设置了-s隐藏选项,所以年龄输入时会看不到内容
对于性别处,输入一个字符,无论是什么都会直接自动运行下一步,甚至不需要回车