---
title: "Shell脚本异步执行实现"
id: "245"
type: "post"
slug: "shell%e8%84%9a%e6%9c%ac%e5%bc%82%e6%ad%a5%e6%89%a7%e8%a1%8c%e5%ae%9e%e7%8e%b0"
published_at: "2019-11-12T07:52:01+00:00"
modified_at: "2020-01-02T13:50:47+00:00"
url: "https://www.hitsword.org/2019/245.html"
markdown_url: "https://www.hitsword.org/2019/245.md"
excerpt: "在写Shell脚本调用HTTP接口的时候，遇到了异步执行的需求，实现方法如下： 脚本test1.sh"
taxonomy_category:
  - "Shell脚本"
taxonomy_post_tag:
  - "Shell脚本"
  - "异步"
---

# Shell脚本异步执行实现

在写Shell脚本调用HTTP接口的时候，遇到了异步执行的需求，实现方法如下：  
 脚本test1.sh

```
#!/bin/bash
echo '开始脚本 test1'
#调用test2脚本并在后台运行
nohup sh test2.sh >/dev/null 2>&1 &
date
echo '结束脚本 test1'
```

- &：是指在后台运行，当用户退出（挂起）的时候，命令自动跟着结束
- nohup：不挂断的运行，注意并没有后台运行的功能，就是指用nohup运行命令可以使命令永久的执行下去，和用户终端没有关系，例如我们断开SSH连接都不会影响他的运行，注意了nohup没有后台运行的意思；&才是后台运行

脚本test2.sh

```
#!/bin/bash
echo '开始脚本 test2' >> test2.txt
date >> test2.txt
sleep 60
date >> test2.txt
echo '结束脚本 test2' >>test2.txt
```

通过test1.sh脚本嵌套test2.sh脚本执行，实现test2.sh和test1.sh异步操作
