shell脚本之一:shell脚本介绍,


一、shell脚本介绍

(一)脚本案例及介绍:

#!/bin/bash

LOG_DIR=/var/log

ROOT_UID=0
if ["$UID -ne "$ROOT_UID"]
then
    echo "must be root run this script."
    exit 1
 fi
 
 cd $ LOG_DIR || {
     
  echo "cannot change to necessary directory"
  exit 1
 }
 
 cat /dev/null>message && {
     echo "logs cleaned up."
     exit 0
 }
 
 echo "logs cleaned fail."
 exit 1
 

(二)shell脚本解释器:

[root@web01 ~]# echo $SHELL
/bin/bash
[root@web01 ~]# ll  /bin/sh
lrwxrwxrwx. 1 root root 4 Oct 10  2018 /bin/sh -> bash

解释器默认为bash,如果脚本中不标明解释器,默认调用bash。

批量注释方法1:ctrl+shift+v,光标向下移动,shitf+a,第一行前#,esc。

批量注释方法2:将要注释的内容写在下面符号内::<<EOF XXX EOF.冒号表示什么的都不做。

批量注释方法3:cat >/dev/null<<EOF XXX EOF

(三)shell执行方法:

方法1:bash,sh

方法2:/path/script-name 或者./script-name

方法3:source script-name 或者.script-name

方法4:sh<script-name 或者 cat scripts-name | sh

实例:

[root@web01 scripts01]# bash test.sh 
i am oldboy teacher.
[root@web01 scripts01]# sh test.sh 
i am oldboy teacher.
[root@web01 scripts01]# ./test.sh
-bash: ./test.sh: Permission denied
[root@web01 scripts01]# /server/scripts01/test.sh
-bash: /server/scripts01/test.sh: Permission denied
[root@web01 scripts01]# ls -l test.sh 
-rw-r--r-- 1 root root 127 Jan 18 23:12 test.sh
[root@web01 scripts01]# chmod +x test.sh 
[root@web01 scripts01]# /server/scripts01/test.sh
i am oldboy teacher.
[root@web01 scripts01]# sh < test.sh 
i am oldboy teacher.
[root@web01 scripts01]# cat test.sh | sh
i am oldboy teacher.
[root@web01 scripts01]#

实例:

[root@web01 scripts01]# chkconfig --list | grep 3:on | awk '{print "chkconfig", $1,"off"}' 
chkconfig crond off
chkconfig network off
chkconfig rsyslog off
chkconfig sshd off
[root@web01 scripts01]# chkconfig --list | grep 3:on | awk '{print "chkconfig", $1,"off"}' | bash
[root@web01 scripts01]# chkconfig --list | grep 3:on

方法3:source script-name 或者.script-name

[root@web01 scripts01]# cat test1.sh 
user=`whoami`
[root@web01 scripts01]# sh test1.sh 
[root@web01 scripts01]# echo $user

[root@web01 scripts01]# 
# sh 相当于在当前shell下新开启一个子shell,所以echo $user,在当前开启shell下执行。
[root@web01 scripts01]# source test1.sh 
[root@web01 scripts01]# echo $user
root
[root@web01 scripts01]#
#source 相当于在当前shell下执行。
父shell
子shell
使用source 和.来执行脚本,相当于在一个shell执行脚本,可以相互调用。
使用bash或者sh执行脚本,开启一个新的shell,或者开启子shell。
[root@web01 scripts01]# vim 1.sh
sh test1.sh
echo $user
[root@web01 scripts01]# sh 1.sh

[root@web01 scripts01]# cat 1.sh
sh test1.sh
echo $user

[root@web01 scripts01]# cat 1.sh
. ./test1.sh
echo $user

[root@web01 scripts01]# sh 1.sh
root
使用source 和.可以相互调用父shell和子shell。

(四)shell执行过程:

父shell脚本-外部命令-子脚本-父shell

父shell和子shell之间不能相互调用:如果希望相互调用,使用source和点.来执行。

shell脚本编程规范和习惯:

①开头加解释器:#!/bin/bash

②附带作者及版权信息:oldboy at dddd

③脚本扩展名:.sh

④脚本存放固定位置:/server/scripts

⑤脚本中不使用中文。

⑥成对的符号一次书写完成。中括号,两边需空格

⑦循环格式一次性输入完成。

相关内容

    暂无相关文章