Shell脚本(待扩展)

350 阅读2分钟

Shell脚本

Shell脚本编写

脚本文件编写时一般在文件开头添加(#! /bin/bash or #! /bin/sh)并独处一行,而后开始脚本编写;

#代表注释,但是和!组合#!用来声明解释脚本的程序;可以根据脚本执行方式的不同,选择开头写与不写


Shell脚本执行方式

Shell脚本执行大体有三种执行方式(script-name均是带有路径):

  • bash/sh script-name
  • source/. script-name
  • script-name

bash/sh script-name

使用此种方式执行脚本,可以选择在脚本中不声明解释程序,因为外部指明解释程序


soruce/. script-name

此处使用.执行脚本时,必须添加路径,否则会报相应的错误


script-name

直接使用脚本名字执行,文件执行用户必须是可执行的,可以通过chmod增加可执行权限


注:

  • 第一种和第三种方式都会在当前Shell进程外启动子Shell进程,可以在Shell脚本中echo ?打印进程ID可知
  • 一般建议在脚本头行声明解释程序,而且在脚本执行时指定解释程序,避免执行漏写等问题

Shell脚本文件中调用其他脚本执行

从一个脚本中调用另外脚本执行有三种方式,fork, exec, source

Command Explanation
fork 由名知义,新开一个子Shell进程,子Shell继承父进程环境变量,但不能将自己的环境变量传递给父Shell
exec 在同一个Shell进程中执行,但父脚本exec命令之后的内容不会再被执行
source 在同一个Shell进程中执行,相当于两个脚本合并成一个脚本,相应环境变量可以相互取用
super.sh
#! /bin/bash
x=10
y=20
if [ $x -gt $y ]
then
    echo "x is greater than y"
else
    echo "y is greater than x"
fi
echo ?

# 测试调用执行子脚本方式fork, exec,source
A=1
# Mark each name to be passed to child processes in the environment
export -p A

case $1 in
    "exec")
        echo -e "==> using exec ..."
        exec ./subShell.sh;;
    "source")
        echo -e "==> using source ..."
        source ./subShell.sh;;
    *)
        echo -e "==> using fork for default ..."
        ./subShell.sh;;
esac        

echo -e "in super script variable A = $A\n"        

subShell.sh
#! /bin/bash

echo "PID for subShell = ?"
echo "In subShell script get variable A = $A from super script(super.sh)"

A=2
export A
echo -e "in subShell.sh variable A = $A"

注:相应的执行脚本在文件夹内可以查询,执行结果如图: