Shell脚本有运维工程师应该知道的三种执行方式
Shell脚本是运维工程师必备的技能。现在大部分企业招聘都要求掌握一两个shell、python、php等。对于运维工程师来说,Shell无疑是最好的选择,因为Shell支持数千条Linux命令。对于一些常见的企业应用来说,使用shell脚本更符合Linux运维的三个基本原则:简单、易用、高效。
运行shell脚本有三种方式
- 运行bash或sh(或者cat脚本路径|bash,本质是一样的)
[root@shell shell]# cat first.sh#!/bin/bash#date:2019-06-11cd /var/log/pwdls -l messages[root@shell shell]# bash first.sh/var/log-rw-------. 1 root root 915415 6月 12 04:01 messages
2.使用绝对路径或相对路径运行,需要执行权限(chmod + x 脚本路径)
[root@shell shell]# chmod +x first.sh[root@shell shell]# ll first.sh-rwxr-xr-x 1 root root 61 6月 12 04:32 first.sh[root@shell shell]# ./first.sh/var/log-rw-------. 1 root root 915542 6月 12 05:01 messages
3.source 或“.”在当前shell下执行相当于在命令行执行命令
[root@shell shell]# source first.sh/var/log-rw-------. 1 root root 915542 6月 12 05:01 messages[root@shell log]#
总结:方法一、方法三运行脚本时,不需要添加执行权限;当脚本以方法1和2执行时,会打开一个新的子shell来执行。脚本执行后,返回主shell。同时,脚本执行的结果返回到主shell,但脚本中创建的变量在子路径退出时会丢失。
通常在执行自己编写的脚本时使用方法1和方法2。方法3用于两种情况:一是加载环境变量(如source /etc/profile);二是加载环境变量(如source /etc/profile);一种是在脚本过程中调用另一个。
如果你了解了三种执行shell脚本方式的区别,猜猜执行下面两个脚本后变量A的值会是多少?
[root@shell shell]# cat first.sh#!/bin/bash#date:2019-06-11cd /var/log/A=$(pwd)ls -l messages[root@shell shell]# bash first.sh-rw-------. 1 root root 915542 6月 12 05:01 messages[root@shell shell]# echo $A
[root@shell shell]# cat first.sh#!/bin/bash#date:2019-06-11cd /var/log/A=$(pwd)ls -l mes
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
code前端网