Linux下脚本的运行方式有四种,以脚本test.sh为例:
第一种:bash test.sh
第二种:./test.sh
第三种:. test.sh
第四种:source test.sh
第一种和第二种都是开启一个子进程运行脚本,但是第二种方式运行脚本的前提是脚本有可执行权限,需执行命令chmod +x test.sh;
第三种和第四种都是在当前进程运行脚本。
[root@hangtian01 ~]# cat test.sh #查看脚本的内容
#!/bin/sh
i=1
# 输出变量i
echo $i
# 输出当前的进程号
echo $$
[root@hangtian01 ~]# ll
total 68
-rw-------. 1 root root 2511 Dec 21 17:33 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Desktop
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Documents
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Downloads
-rw-r--r--. 1 root root 2559 Dec 21 17:36 initial-setup-ks.cfg
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Music
drwxr-xr-x. 2 root root 4096 Dec 21 17:45 perl5
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Pictures
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Public
-rw-------. 1 root root 1766 Feb 20 09:40 root
-rw-r--r--. 1 root root 395 Feb 20 09:40 root.pub
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Templates
-rwxr-xr-x. 1 root root 65 Mar 4 16:08 test
-rwxr-xr-x. 1 root root 78 Mar 4 17:01 test.sh
-rw-r--r--. 1 root root 0 Feb 26 11:40 tiantian
drwxr-xr-x. 2 root root 4096 Jan 11 10:20 Videos
-rw-------. 1 root root 1766 Feb 20 09:40 yes
-rw-r--r--. 1 root root 395 Feb 20 09:40 yes.pub
[root@hangtian01 ~]# bash test.sh
1
7442
[root@hangtian01 ~]# . test.sh
1
3567
[root@hangtian01 ~]# source test.sh
1
3567