Linux编程:命令手册使用与程序脚本优化指南
1. Linux命令手册的使用
在Linux系统中,命令手册是获取命令详细信息的重要工具。
1.1 查看特定命令手册
要查看
unlink
命令的手册,可以在控制台中输入
man unlink
。手册通常从第1部分开始,打开找到的第一个手册。如果不指定章节编号,可能会得到像
printf
和
unlink
这样的命令手册,而不是C函数和系统调用的手册。因此,查看打开的手册页的标题,以确保阅读的是正确的手册是个好习惯。
例如,要查看
getopt()
函数的手册,可以输入
man 3 getopt
。大多数涵盖库函数和系统调用的手册页通常包含以下标题:
| 标题 | 说明 |
| ---- | ---- |
| Name | 函数名称 |
| Synopsis | 函数原型及所需包含的头文件 |
| Description | 函数描述 |
| Return value | 返回值说明 |
| Environment | 环境相关信息 |
| Attributes | 属性说明 |
| Conforming to | 遵循的标准 |
| Notes | 注意事项 |
| Example | 示例 |
| See also | 相关参考 |
其中,
Synopsis
标题列出了特定函数所需包含的头文件,这非常有用,因为我们很难记住每个函数及其对应的头文件。
此外,输入
man man
可以获取关于手册本身的很多有用信息,建议至少浏览一下。
1.2 在手册中搜索信息
如果不知道特定命令、函数或系统调用的确切名称,可以使用
apropos
命令在系统的所有手册中搜索。具体操作步骤如下:
1. 输入
apropos directory
,会列出一长串相关的手册页,每个手册后面括号内的数字表示该手册所在的章节。
2. 若要将搜索范围缩小到仅第3节(库调用),可输入
apropos -s 3 directory
。
3. 进一步缩小搜索范围,输入
apropos -s 3 -a remove directory
,其中
-a
选项表示“和”,意味着搜索结果中必须同时包含
remove
和
directory
。
apropos
命令通过搜索手册页的描述和关键字来查找信息。如果不使用
-a
选项,它会搜索包含任一或两个关键字的结果。更多关于
apropos
命令工作原理的信息可以在其手册页(
man apropos
)中查看。
如果只想了解特定命令或函数的简要说明,可以使用
whatis
命令,例如:
$> whatis getopt
getopt (1) - parse command options (enhanced)
getopt (3) - Parse command-line options
$> whatis creat
creat (2) - open and possibly create a file
$> whatis opendir
opendir (3) - open a directory
2. 让程序易于脚本化
Linux和其他Unix系统具有强大的脚本支持。Unix的理念是使系统易于开发,其中一个特点是可以将一个程序的输出作为另一个程序的输入,从而利用现有程序构建新工具。在为Linux创建程序时,应始终牢记这一点。Unix哲学是编写只做一件事且做得很好的小程序,通过组合这些小程序可以编写shell脚本。
2.1 技术要求
要实现程序的脚本化,需要一台安装了GCC和Make的Linux计算机,最好通过元包或组安装的方式进行安装。为了获得最佳兼容性,建议使用Bash shell。可以在终端中运行
echo $SHELL
来检查当前使用的shell,如果是Bash,会显示
/bin/bash
。
2.2 返回值及其读取
在Linux和其他Unix及类Unix系统中,返回值非常重要,在C编程中也是如此。大多数C函数通过
return
语句返回值,
main()
函数也可以使用
return
语句将值返回给shell。
下面通过一个示例来演示返回值的用途、读取和解释方法:
1.
调查程序的返回值
:使用
test
命令测试文件或目录是否存在,
-e
选项表示存在。
test
命令不输出任何内容,仅以返回值退出。执行以下命令并记录返回值:
$> test -e /
$> echo $?
0
$> test -e /asdfasdf
$> echo $?
1
从上述结果可知,当文件或目录存在时,
test
命令返回0,否则返回1。
-
编写脚本
:将以下代码保存为
exist.sh文件:
#!/bin/bash
# Check if the user supplied exactly one argument
if [ "$#" -ne 1 ]; then
echo "You must supply exactly one argument."
echo "Example: $0 /etc"
exit 1 # Return with value 1
fi
# Check if the file/directory exists
test -e "$1" # Perform the actual test
if [ "$?" -eq 0 ]; then
echo "File or directory exists"
elif [ "$?" -eq 1 ]; then
echo "File or directory does not exist"
exit 3 # Return with a special code so other
# programs can use the value to see if a
# file dosen't exist
else
echo "Unknown return value from test..."
exit 1 # Unknown error occured, so exit with 1
fi
exit 0 # If the file or directory exists, we exit
- 使脚本可执行 :执行以下命令:
$> chmod +x exist.sh
- 测试脚本 :使用存在和不存在的目录测试脚本,并检查每次运行后的退出代码:
$> ./exist.sh
You must supply exactly one argument.
Example: ./exist.sh /etc
$> echo $?
1
$> ./exist.sh /etc
File or directory exists
$> echo $?
0
$> ./exist.sh /asdfasdf
File or directory does not exist
$> echo $?
3
- 根据退出代码执行操作 :
$> ./exist.sh / && echo "Nice, that one exists"
File or directory exists
Nice, that one exists
$> ./exist.sh /asdf && echo "Nice, that one exists"
File or directory does not exist
&&
表示“和”,可以将上述命令理解为一个
if
语句。如果
exist.sh
的退出代码为0,则执行
echo
命令;否则,
echo
命令不会执行。
- 更复杂的操作 :
$> ./exist.sh /asdf &> /dev/null; \
> if [ $? -eq 3 ]; then echo "That doesn't exist"; fi
That doesn't exist
上述命令将脚本的所有输出重定向到
/dev/null
,然后使用完整的
if
语句检查错误代码3。如果遇到错误代码3,则使用
echo
打印消息。
test
命令是一个用于测试文件和目录、比较值等的小工具。在脚本中,使用
$?
变量来检查
test
命令的返回值,同时还使用了其他特殊变量:
-
$#
:包含传递给脚本的参数数量,类似于C语言中的
argc
。
-
$0
:包含程序的名称,类似于C语言中的
argv[0]
。
-
$1
:存储传递给程序的第一个参数,在本例中是要测试的文件名或目录。
脚本通过
exit
语句设置返回值。如果用户没有提供恰好一个参数,脚本以代码1退出;如果文件或目录存在,脚本以代码0退出;如果文件或目录不存在,脚本以代码3退出。其他脚本可以获取我们脚本的返回值并据此采取相应的操作。
此外,
test
命令还有更多的测试和比较功能,可在其手册页(
man 1 test
)中查看。如果不熟悉Bash和shell脚本编程,可以查看
man 1 bash
获取有用信息。
&&
的相反操作符是
||
,表示“或”,例如:
$> ./exist.sh / || echo "That doesn't exist"
File or directory exists
$> ./exist.sh /asdf || echo "That doesn't exist"
File or directory does not exist
That doesn't exist
3. 以相关返回值退出程序
在C程序中,可以使用两种不同的方法以相关返回值退出程序,下面通过两个示例来演示:
3.1 使用
return
语句
将以下代码保存为
functions_ver1.c
文件:
#include <stdio.h>
int func1(void);
int func2(void);
int main(int argc, char *argv[])
{
printf("Inside main\n");
printf("Calling function one\n");
if (func1())
{
printf("Everything ok from function one\n");
printf("Return with 0 from main - all ok\n");
return 0;
}
else
{
printf("Caught an error from function one\n");
printf("Return with 1 from main - error\n");
return 1;
}
return 0; /* We shouldn't reach this, but just in case */
}
int func1(void)
{
printf("Inside function one\n");
printf("Calling function two\n");
if (func2())
{
printf("Everything ok from function two\n");
return 1;
}
else
{
printf("Caught an error from function two\n");
return 0;
}
}
int func2(void)
{
printf("Inside function two\n");
printf("Returning with 0 (error) from function two\n");
return 0;
}
编译并运行该程序:
$> gcc functions_ver1.c -o functions_ver1
$> ./functions-ver1
Inside main
Calling function one
Inside function one
Calling function two
Inside function two
Returning with 0 (error) from function two
Caught an error from function two
Caught an error from function one
Return with 1 from main – error
检查返回值:
$> echo $?
1
3.2 使用
exit()
函数
将以下代码保存为
functions_ver2.c
文件:
#include <stdio.h>
#include <stdlib.h>
int func1(void);
int func2(void);
int main(int argc, char *argv[])
{
printf("Inside main\n");
printf("Calling function one\n");
if (func1())
{
printf("Everything ok from function one\n");
printf("Return with 0 from main - all ok\n");
return 0;
}
else
{
printf("Caught an error from funtcion one\n");
printf("Return with 1 from main - error\n");
return 1;
}
return 0; /* We shouldn't reach this, but just in case */
}
int func1(void)
{
printf("Inside function one\n");
printf("Calling function two\n");
if (func2())
{
printf("Everything ok from function two\n");
exit(0);
}
else
{
printf("Caught an error from function two\n");
exit(1);
}
}
编译并运行该程序:
$> gcc functions_ver2.c -o functions_ver2
$> ./functions_ver2
Inside main
Calling function one
Inside function one
Calling function two
Inside function two
Returning with (error) from function two
检查返回值:
$> echo $?
1
在C语言中,0被视为假或错误,而其他值被视为真(或正确),这与返回给shell的值相反。对于shell来说,0表示“一切正常”,其他值表示错误。
两种版本的区别在于函数和整个程序的返回方式。在第一个版本中,每个函数按调用顺序返回给调用它的函数;在第二个版本中,每个函数使用
exit()
函数直接退出程序,并将指定的值返回给shell。第二个版本不是最佳实践,因为如果其他人在另一个程序中使用该函数,函数突然退出整个程序会让人意外。
程序在Linux中就像程序中的函数一样,通过
return
语句返回给调用它的父进程(通常是shell)。以下是一个简单的流程图展示了Bash调用程序以及函数之间的调用和返回关系:
graph LR
A[Bash] --> B[main()]
B --> C[func1()]
C --> D[func2()]
D --> C
C --> B
B --> A
通过以上内容,我们学习了如何使用Linux命令手册、编写易于脚本化的程序以及以相关返回值退出C程序,这些技巧将有助于我们更好地进行Linux编程和脚本开发。
Linux编程:命令手册使用与程序脚本优化指南
4. 重定向标准输入、输出和错误输出
在Linux编程中,重定向标准输入(stdin)、标准输出(stdout)和标准错误输出(stderr)是非常实用的技巧,它能让程序之间更好地交互,也方便我们对程序的输入输出进行管理。
4.1 重定向标准输出
重定向标准输出可以将程序的输出结果保存到文件中,而不是显示在终端上。以下是具体的操作步骤:
1. 编写一个简单的C程序,将一些信息输出到标准输出。以下是示例代码,保存为
output.c
:
#include <stdio.h>
int main() {
printf("This is standard output.\n");
return 0;
}
- 编译这个程序:
$> gcc output.c -o output
-
重定向标准输出到文件
output.txt:
$> ./output > output.txt
执行上述命令后,程序的输出不会显示在终端上,而是被保存到了
output.txt
文件中。可以使用
cat
命令查看文件内容:
$> cat output.txt
This is standard output.
4.2 重定向标准错误输出
重定向标准错误输出可以将程序的错误信息保存到文件中。以下是一个示例,模拟程序产生错误并将错误信息重定向到文件。示例代码保存为
error.c
:
#include <stdio.h>
#include <stdlib.h>
int main() {
fprintf(stderr, "This is a standard error message.\n");
exit(1);
}
编译并运行程序,将错误信息重定向到
error.txt
:
$> gcc error.c -o error
$> ./error 2> error.txt
使用
cat
命令查看
error.txt
文件内容:
$> cat error.txt
This is a standard error message.
4.3 重定向标准输入
重定向标准输入可以让程序从文件中读取输入,而不是等待用户在终端输入。以下是一个简单的示例,程序从文件中读取内容并输出。示例代码保存为
input.c
:
#include <stdio.h>
int main() {
char buffer[100];
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
printf("Read: %s", buffer);
}
return 0;
}
创建一个包含一些内容的文件
input.txt
:
$> echo "This is input data." > input.txt
编译并运行程序,将文件内容作为标准输入:
$> gcc input.c -o input
$> ./input < input.txt
Read: This is input data.
5. 使用管道连接程序
管道是Linux系统中一个强大的特性,它可以将一个程序的输出作为另一个程序的输入,从而实现程序之间的协作。
5.1 简单管道示例
以下是一个简单的管道示例,使用
ls
命令列出当前目录下的文件和文件夹,并将结果通过管道传递给
grep
命令,筛选出包含
txt
的文件:
$> ls | grep txt
input.txt
output.txt
error.txt
在这个示例中,
ls
命令的输出作为
grep
命令的输入,
grep
命令根据指定的模式筛选出符合条件的内容。
5.2 复杂管道示例
我们可以构建更复杂的管道,将多个程序连接起来。例如,统计当前目录下所有
.c
文件的行数。可以使用
find
命令查找所有
.c
文件,然后将结果通过管道传递给
xargs
命令,再将
xargs
的输出传递给
wc -l
命令进行行数统计:
$> find . -name "*.c" | xargs wc -l
10 ./output.c
8 ./error.c
12 ./input.c
30 total
以下是这个过程的流程图:
graph LR
A[find . -name "*.c"] --> B[xargs]
B --> C[wc -l]
6. 编写管道友好的程序
为了让程序能够更好地与管道配合使用,我们需要编写管道友好的程序。管道友好的程序应该满足以下几点要求:
1.
处理标准输入
:程序应该能够从标准输入读取数据,而不是依赖于命令行参数或固定的文件。
2.
输出到标准输出
:程序的输出应该输出到标准输出,这样可以方便地将输出传递给其他程序。
以下是一个简单的管道友好程序示例,将输入的内容转换为大写并输出。示例代码保存为
upper.c
:
#include <stdio.h>
#include <ctype.h>
int main() {
int c;
while ((c = getchar()) != EOF) {
putchar(toupper(c));
}
return 0;
}
编译并运行这个程序,结合管道使用:
$> gcc upper.c -o upper
$> echo "hello world" | ./upper
HELLO WORLD
7. 读取环境变量
在Linux编程中,环境变量是一种非常有用的机制,它可以存储系统和用户的配置信息,程序可以读取这些环境变量来获取必要的信息。
7.1 查看环境变量
可以使用
env
命令查看当前系统的所有环境变量:
$> env
USER=your_username
HOME=/home/your_username
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
...
7.2 在C程序中读取环境变量
在C程序中,可以使用
getenv()
函数来读取环境变量。以下是一个示例代码,保存为
env_read.c
:
#include <stdio.h>
#include <stdlib.h>
int main() {
char *path = getenv("PATH");
if (path != NULL) {
printf("The value of PATH is: %s\n", path);
} else {
printf("PATH environment variable not found.\n");
}
return 0;
}
编译并运行这个程序:
$> gcc env_read.c -o env_read
$> ./env_read
The value of PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
通过以上内容,我们进一步学习了Linux编程中重定向、管道、编写管道友好程序以及读取环境变量等重要技巧。这些技巧可以帮助我们更好地进行程序开发和系统管理,提高程序的灵活性和可交互性。在实际的Linux编程中,合理运用这些技巧,能够让我们的程序更加高效、实用。
1341




被折叠的 条评论
为什么被折叠?



