网站建设服务器百度云,建设网站要多长时间,wordpress模板 手机,企业彩页设计模板声明#xff01; 学习视频来自B站up主 **泷羽sec** 有兴趣的师傅可以关注一下#xff0c;如涉及侵权马上删除文章#xff0c;笔记只是方便各位师傅的学习和探讨#xff0c;文章所提到的网站以及内容#xff0c;只做学习交流#xff0c;其他均与本人以及泷羽sec团队无关 学习视频来自B站up主 **泷羽sec** 有兴趣的师傅可以关注一下如涉及侵权马上删除文章笔记只是方便各位师傅的学习和探讨文章所提到的网站以及内容只做学习交流其他均与本人以及泷羽sec团队无关切勿触碰法律底线否则后果自负有兴趣的小伙伴可以点击下面连接进入b站主页[B站泷羽sec](https://space.bilibili.com/350329294) 脚本之间的相互调用
在 Shell 脚本中可以通过多种方式实现脚本之间的调用 直接调用
bash
# 假设 2.sh 包含以下内容
echo hello# 创建 3.sh内容如下
. 2.sh # 或者 source 2.sh 说明 - source或 .将被调用脚本2.sh加载到当前 Shell 进程中执行变量和环境会共享。例如 - 2.sh 中的变量在 3.sh 中依然可用。 - 没有启动新的 Shell 进程。
执行结果 运行 bash 3.sh 输出 hello 2. 使用子 Shell 调用 bash
假设 2.sh 包含以下内容
echo hello# 创建 3.sh内容如下
bash 2.sh说明 - **bash 或其他 Shell 直接运行脚本**被调用脚本在独立的子 Shell 中运行变量和环境不共享。 - 适用于需要隔离上下文的情况。 执行结果 运行 bash 3.sh 输出hello
3. 使用脚本作为函数库 将常用的函数或逻辑放在一个脚本中供其他脚本调用。例如
创建 utils.sh
bash
log_message() {echo Log: $1
}创建 main.sh
bash
source utils.sh
log_message This is a test message.执行结果 运行接过 Log: This is a test message. 重定向输出重定向和输入重定向
重定向用于将输入或输出流从默认位置如终端重定向到文件或其他流。### **1. 输出重定向**
将命令的输出保存到文件中。
语法
bash
command file # 覆盖写入
command file # 追加写入示例
bash
echo Hello, World! output.txt
echo Appending line output.txt说明 - 覆盖写入文件中原有内容会被清除。 - 追加写入内容会追加到文件末尾。 2. 输入重定向
将文件内容作为命令的输入。语法
bash
command file
#### **示例**
bash
cat input.txt说明 - 将文件 input.txt 的内容作为 cat 的输入。
---
3. 错误输出重定向
默认情况下错误输出标准错误流不会与标准输出一起被重定向。可以单独或同时重定向错误输出。
语法
bash
command 2 file # 将错误输出重定向到文件覆盖写入
command 2 file # 将错误输出追加到文件末尾
command file 21 # 同时重定向标准输出和错误输出 . 同时重定向标准输出和错误输出语法
bash
command output.txt 21 # 输出和错误都写入 output.txt
#### **示例**
bash
ls /valid/path /invalid/path all_output.txt 21说明 - 21 表示将文件描述符 2错误输出指向文件描述符 1标准输出。 - 所有输出标准和错误都保存到 all_output.txt。
---
Here Document多行输入重定向
将多行内容作为命令的输入。#### **语法
bash
command EOF
多行内容
EOF
#### **示例**
bash
cat EOF
This is line 1
This is line 2
EOF 说明 - EOF 是结束标志可以自定义如 END。 - 多行内容会作为输入传递给 cat。
文件描述符
在 Unix 系统中每个进程有三个默认的文件描述符 1. 标准输入stdin文件描述符0 - 默认从终端或文件读取输入。 - 可通过 重定向输入。 2. 标准输出stdout文件描述符1 - 默认将命令的输出打印到终端。 - 可通过 或 重定向输出。 3. 标准错误stderr文件描述符2 - 默认将错误信息输出到终端。 - 可通过 2 重定向错误输出。
---
综合示例
示例 1同时重定向标准输出和错误输出 bash # 脚本内容 test.sh echo This is standard output ls /invalid/path echo This is another standard output
# 执行并重定向 bash test.sh output.txt 2 error.txt
结果 - output.txt 包含 This is standard output This is another standard output - error.txt 包含 ls: cannot access /invalid/path: No such file or directory
---
示例 2将文件内容追加写入另一文件 bash # 将输入文件的内容追加到目标文件中 cat input.txt output.txt ### **示例 3错误与标准输出的分离与合并** bash # 创建脚本 combine.sh echo This is standard output ls /non_existent_file
# 运行脚本并分别保存输出和错误 bash combine.sh stdout.txt 2 stderr.txt
# 同时合并输出和错误 bash combine.sh combined.txt 21
**结果** - stdout.txt 包含 This is standard output - stderr.txt 包含 ls: cannot access /non_existent_file: No such file or directory - combined.txt 包含两部分内容。