Linux(shell脚本的常用执行方式)

92 阅读1分钟

shell脚本的常用执行方式

第一种:采用 bash 或 sh+脚本的相对路径或绝对路径(不用赋予脚本+x 权限) sh+脚本的相对路径

[lanyan@lanyan shells]$ sh ./helloworld.sh
Helloworld

sh+脚本的绝对路径

[atguigu@hadoop101 shells]$ sh /home/atguigu/shells/helloworld.sh
helloworld

bash+脚本的相对路径

[lanyan@lanyan shells]$ bash ./helloworld.sh
Helloworld

bash+脚本的绝对路径

[lanyan@lanyan shells]$ bash /home/atguigu/shells/helloworld.sh
Helloworld

第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x) ①首先要赋予 helloworld.sh 脚本的+x 权限

[lanyan@lanyan shells]$ chmod +x helloworld.sh

②执行脚本 相对路径

[lanyan@lanyan shells]$ ./helloworld.sh
Helloworld

绝对路径

[lanyan@lanyan shells]$ /home/atguigu/shells/helloworld.sh
Helloworld

注意:第一种执行方法,本质是 bash 解析器帮你执行脚本,所以脚本本身不需要执行 权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。 【了解】第三种:在脚本的路径前加上“.”或者 source ①有以下脚本

[lanyan@lanyan shells]$ cat test.sh
#!/bin/bash
A=5
echo $A

②分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:

[lanyan@lanyan shells]$ bash test.sh
[lanyan@lanyan shells]$ echo $A
​
[lanyan@lanyan shells]$ sh test.sh
[lanyan@lanyan shells]$ echo $A
​
[lanyan@lanyan shells]$ ./test.sh
[lanyan@lanyan shells]$ echo $A
​
[lanyan@lanyan shells]$ . test.sh
[lanyan@lanyan shells]$ echo $A
5

第一次发布文章写的不好多见谅