shell
一、shell概述
shell是一个命令行解释器,它接收应用程序/用户命令,然后调用操作系统内核。
Shell还是一个功能相当强大的编程语言,易编写、易调试、灵活性强。
Linux提供的shell解析器
root@zhangkun:~# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/bash
/bin/dash
/usr/bin/dash
root@zhangkun:~# echo $SHELL
/bin/bash
二、第一个shell脚本
先新建一个sh脚本文件
root@zhangkun:~# mkdir study
root@zhangkun:~/study# touch hello.sh
root@zhangkun:~/study# vi hello.sh
在helloworld.sh中输入如下内容
#!/bin/bash
echo "Hello,world"
脚本常用的执行方式
1、第一种采用bash或sh+脚本的相对路径或者绝对路径(不用赋予脚本+x权限)
sh+脚本的相对路径
root@zhangkun:~/study# sh hello.sh
Hello,world
sh+脚本的绝对路径
root@zhangkun:~/study# sh /root/study/hello.sh
Hello,world
bash+脚本的相对路径
root@ zhangkun:~/study# bash hello.sh
Hello,world
bash+脚本的绝对路径
root@ zhangkun:~/study# bash /root/study/hello.sh
Hello,world
2、第二种:采用输入脚本的绝对路径和相对路径执行脚本(必须具有可执行权限+x)
1、首先赋予helloworld.sh脚本+x权限
root@zhangkun:~/study# chmod +x hello.sh
2、./+脚本名
root@zhangkun:~/study# ./hello.sh
Hello,world
3、/+绝对路径
root@ zhangkun:~/study# /root/study/hello.sh
Hello,world
第三种:在脚本的路径前加上”. ”或者source命令
root@zhangkun:~/study# source hello.sh
Hello,world
root@zhangkun:~/study# source /root/study/hello.sh
Hello,world
root@zhangkun:~/study# . hello.sh
Hello,world
source是shell的内嵌
root@zhangkun:~/study# type source
source is a shell builtin
前两种都是在当前shell中打开一个子shell来执行脚本内容,当脚本内容结束,则子shell关闭,回到父shell中。
第三种,也就是使用在脚本路径前加”.”或者source的方式,可以使脚本内容在当前shell里执行,而无需打开子shell,也就是为什么我们每次修改完/etc/profile文件以后,需要source一下的原因。
三、父子shell
查看bash进程
root@zhangkun:~/study# ps -f
UID PID PPID C STIME TTY TIME CMD
root 1623611 1623417 0 Jul16 pts/4 00:00:00 -bash
root 2973460 1623611 0 16:18 pts/4 00:00:00 ps -f
在敲一下bash,生成一个bash的子进程
root@ zhangkun:~/study# bash
root@ zhangkun:~/study# ps -f
UID PID PPID C STIME TTY TIME CMD
root 1623611 1623417 0 Jul16 pts/4 00:00:00 -bash
root 2975205 1623611 0 16:19 pts/4 00:00:00 bash
root 2975216 2975205 0 16:19 pts/4 00:00:00 ps -f
后面进行的操作是在子shell中进行。
然后执行exit退出子shell
root@zhangkun:~/study# exit
exit
root@zhangkun:~/study# ps -f
UID PID PPID C STIME TTY TIME CMD
root 1623611 1623417 0 Jul16 pts/4 00:00:00 -bash
root 2979056 1623611 0 16:21 pts/4 00:00:00 ps -f
开子shell和不开子shell的区别在于,环境变量的继承关系,如在子shell中设置的当前变量,父shell中是不可见的。