在 Linux 系统中,C++ 本身并不能直接编写 Shell 脚本。但是,你可以在 C++ 程序中调用 Shell 脚本,或者将 C++ 代码嵌入到 Shell 脚本中。以下是两种方法的简要说明:
方法一:在 C++ 程序中调用 Shell 脚本
script.sh):#!/bin/bash
echo "Hello from Shell script!"
system() 函数调用 Shell 脚本:#include <cstdlib>
int main() {
system("./script.sh");
return 0;
}
编译并运行 C++ 程序,你将看到 Shell 脚本的输出。
方法二:将 C++ 代码嵌入到 Shell 脚本中
script.cpp):#include <iostream>
int main() {
std::cout << "Hello from C++ code!" << std::endl;
return 0;
}
script.sh),在其中嵌入 C++ 代码:#!/bin/bash
# 编译 C++ 代码
g++ -o script script.cpp
# 运行编译后的 C++ 程序
./script
chmod +x script.sh
请注意,这两种方法都需要你在系统上安装了 C++ 编译器(例如 g++)。