#!/bin/bash

来源:互联网 发布:windows7内存优化 编辑:程序博客网 时间:2024/05/22 10:36
#!/bin/bash: 是指此脚本使用/bin/bash来解释执行。其中,#!是一个特殊的表示符,后面紧跟着解释此脚本的shell路径。bash只是shell的一种,还有很多其它shell,比如:sh,csh,ksh,tcsh等等。

示例演示:
1. #!/bin/bash只能放在第一行,如果后面还有#!,那么只能看成是注释。
这里有三个脚本(脚本都要使用”chmod +x  yourscriptname“命令来获得可执行权限):
mybash_1.sh:
#!/bin/sh
source abc
echo "hello abc"

mybash_2.sh:
#!/bin/bash
source abc
echo "hello abc"

mybash_3.sh:
source abc
echo "hello abc"

执行结果:
[root@localhost winine]$ ./mybash_1.sh 
./mybash_1.sh: line 2: abc: No such file or directory
注:当source命令执行有问题时,sh不再往下面执行。

[root@localhost winine]$./mybash_2.sh 
./mybash_2.sh: line 2: abc: No such file or directory
hello abc
注:当source命令执行有问题时,bash继续执行下面命令。

[root@localhost winine]$./mybash_3.sh 
./mybash_3.sh: line 1: abc: No such file or directory
hello abc
注:自身登录系统所在的shell是bash。所以,当source命令执行有问题时,bash继续执行下面命令。

如果将mybash_1.sh改成:
echo "abc"
#!/bin/sh
source abc
echo "hello abc"
那么,执行结果是:
[root@localhost winine]$ ./mybash_1.sh 
abc
./mybash_1.sh: line 3: abc: No such file or directory
hello abc
注:脚本忽略了第二行“#!/bin/sh",直接使用当前所在的shell(也就是bash)来解释脚本。

如果将mybash_1.sh改成:
#!/bin/sh
#!/bin/bash
source abc
echo "hello abc"
执行结果为:
[root@localhost winine]$ ./mybash_1.sh
./mybash_1.sh: line 3: abc: No such file or directory
注:当执行完source命令时,并没有往下执行。说明,#!/bin/sh这一行起到作用了,但#!/bin/bash并没有起作用。在脚本中,不在第一行的#!/bin/bash,只是一个注释。

2. #!后面的路径一定要正确,不正确会报错。
如果我们把mybash_1.sh中第一行的#!后面加了一个不存在的路径”/home/sh“:
#!/home/sh
source abc
echo "hello abc"
执行结果为:
[root@localhost winine]$ ./mybash_1.sh
-bash: ./tbash1.sh: /home/sh: bad interpreter: No such file or directory
注:系统会提示/home/sh的路径不存在。

3. 如果在某脚本的第一行没有加上”#!+shell路径“这一行,那么,该脚本会默认使用当前用户登录的shell,作为脚本解释器。(这里不做演示)

0 0
原创粉丝点击