linux脚本执行几种方法

发布时间:2023年12月24日

????????脚本程序在linux系统中运行时分为两种环境,一种是在当前shell(称为父shell)开启一个子shell环境,此shell脚本就在这个子shell环境中执行。shell脚本执行完后子shell环境随即关闭,然后又回到父shell中。 第二种是当前shell中执行的,当我们需要利用脚本设置当前环境变量时,应该采取第二种运行脚本的方式。下面分别介绍这两种运行方式的基本命令。

第一种:在子shell环境中运行

1.切换到shell脚本所在的目录(此时,称为工作目录)执行shell脚本:

 cd /data/shell ./hello.sh

./的意思是说在当前的工作目录下执行hello.sh。如果不加上./,bash可能会响应找到不到hello.sh的错误信息。因为目前的工作目录(/data/shell)可能不在执行程序默认的搜索路径之列,也就是说,不在环境变量PASH的内容之中。查看PATH的内容可用 echo $PASH 命令。现在的/data/shell就不在环境变量PASH中的,所以必须加上./才可执行。

2.绝对路径执行

/data/shell/hello.sh

3.直接使用bash 或sh 来执行bash shell脚本

cd /data/shell bash hello.sh

或者

sh hello.sh

第二类: 在当前shell环境中执行

. hello.sh
source hello.sh

上面的内容是我从https://www.cnblogs.com/cofludy/p/16582111.html复制过来的,下面的内容是我自己加的:

例:

一、在子shell中执行

1.用./script_name方式运行脚本

例,下面是脚本1.sh的内容

#! /bin/bash
ps
echo "the pid of this script processing is:echo $$"
echo "the ppid of current shell is:echo $PPID"

然后进入脚本所在目录,运行命令./1.sh执行该脚本,结果如下:

[blondie@localhost 3]$ ./1.sh
    PID TTY          TIME CMD
   2894 pts/1    00:00:00 bash
   3333 pts/1    00:00:00 1.sh
   3334 pts/1    00:00:00 ps
the pid of this script processing is:3333
the ppid of current shell is:2894

由以上结果可知,采用“进入脚本所在目录,然后运行命令./script_name”方式运行脚本是在子shell中执行脚本的。

2.用绝对路径运行脚本,即在命令行中直接以绝对路径方式给出文件,shell会当作可执行文件去执行,如下:

[blondie@localhost 3]$ /home/blondie/linux/3/1.sh
    PID TTY          TIME CMD
   2894 pts/1    00:00:00 bash
   3385 pts/1    00:00:00 1.sh
   3386 pts/1    00:00:00 ps
the pid of this script processing is:3385
the ppid of current shell is:2894

由此可以,在命令行中直接给出脚本的绝对路径,shell就会把文件当成脚本直接运行。且运行脚本的shell是当前shell的子shell.

3.用bash或者sh命令直接执行脚本。

(1)用bash命令执行脚本1.sh:

[blondie@localhost 3]$ bash 1.sh
    PID TTY          TIME CMD
   2894 pts/1    00:00:00 bash
   3431 pts/1    00:00:00 bash
   3432 pts/1    00:00:00 ps

the pid of this script processing is:3431

the ppid of current shell is:2894

(2)用sh命令执行脚本1.sh:

[blondie@localhost 3]$ sh 1.sh
    PID TTY          TIME CMD
   2894 pts/1    00:00:00 bash
   3449 pts/1    00:00:00 sh
   3450 pts/1    00:00:00 ps
the pid of this script processing is:3449
the ppid of current shell is:2894

二、在当前shell中执行脚本

1.用source执行脚本

[blondie@localhost 3]$ source 1.sh
    PID TTY          TIME CMD
   2894 pts/1    00:00:00 bash
   3465 pts/1    00:00:00 ps
the pid of this script processing is:2894
the ppid of current shell is:2885

2.用.执行脚本

[blondie@localhost 3]$ . 1.sh
    PID TTY          TIME CMD
   2894 pts/1    00:00:00 bash
   3472 pts/1    00:00:00 ps
the pid of this script processing is:2894
the ppid of current shell is:2885

文章来源:https://blog.csdn.net/digitalkee/article/details/135178945
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。