您的位置:首页 > 运维架构 > Shell

执行shell的三种方法

2013-11-08 08:39 274 查看
法1:(1)脚本要有可执行权限;(2)执行时要使用命令的绝对路径(当前路径的话是./脚本名)
[root@oldboy /]# cat /mnt/tar.sh
#!/bin/sh
tar cfz /www_html_$(date +%w).tar.sh /var/www/html >/dev/null
[root@oldboy ~]# ll /mnt/tar.sh
-rwxr-xr-x 1 root root 73 Dec 30 00:06 /mnt/tar.sh
[root@oldboy ~]# /mnt/tar.sh
tar: Removing leading `/' from member names
root@oldboy /]# ls
www_html_0.tar.sh

crontab -e
* * * * * /mnt/tar.sh > /dev/null

法2:使用shell解释器程序执行脚本
(1)指定shell解释器程序;(2)并不需要该文件具有可执行的属性
bash /mnt/tar.sh

法3:使用.或者soure运行脚本
在当前的shell中执行source或者.点号加载并执行相关脚本中的命令及语句,而不是产生一个子shell来执行脚本文件中的命令
[root@oldboy ~]# ll /mnt/tar.sh
-rw-r--r-- 1 root root 73 Dec 30 00:06 /mnt/tar.sh
[root@oldboy ~]# . /mnt/tar.sh
[root@oldboy ~]# cd /
[root@oldboy /]# ls
www_html_0.tar.sh

* * * * * /bin/bash /www.tar.sh > /dev/null
* * * * * /mnt/tar.sh > /dev/null
* * * * * /bin/bash /mnt/tar.sh > /dev/null

通过source或者.点号加载执行过的脚本,在脚本结束后脚本中的变量(包括函数)值在当前的shell中依然存在,而sh或者bash则不行。因此,在做shell脚本开发时,如果脚本中有需求引用其他脚本的内容或配置文件时,最好用.点号或source在脚本开头加载该脚本或配置文件,然后在下面的内容可以调用source加载的脚本及文件中的变量及函数等内容。

本文出自 “勇敢的心” 博客,请务必保留此出处http://nihaomingtian.blog.51cto.com/5933084/1321956
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: