每个进程默认打开3个文件描述符:

  • stdin标准输入,从命令行读取数据,文件描述符为0
  • stdout标准输出,向命令行输出数据,文件描述符为1
  • stderr标准错误输出,向命令行输出数据,文件描述符为2 可以用文件重定向将这三个文件重定向到其他文件中。

重定向命令列表

命令 说明

command > file 将stdout重定向到file中

command < file 将stdin重定向到file中

command >> file 将stdout以追加方式重定向到file中

command n> file 将文件描述符n重定向到file中

command n>> file 将文件描述符n以追加方式重定向到file中

输入和输出重定向

echo -e "Hello \c" > output.txt  # 将stdout重定向到output.txt中
echo "World" >> output.txt  # 将字符串追加到output.txt中
 
read str < output.txt  # 从output.txt中读取字符串
 
echo $str  # 输出结果:Hello World

同时重定向stdin和stdout

创建bash脚本:

#! /bin/bash
 
read a
read b
 
echo $(expr "$a" + "$b")

创建input.txt,里面的内容为:

3
4

执行命令:

acs@9e0ebfcd82d7:~$ chmod +x test.sh  # 添加可执行权限
acs@9e0ebfcd82d7:~$ ./test.sh < input.txt > output.txt  # 从input.txt中读取内容,将输出写入output.txt中
acs@9e0ebfcd82d7:~$ cat output.txt  # 查看output.txt中的内容
7
 

权限

ls -l

第一个符号代表文件类型,d是文件夹,l是连接文件,-是普通文件,后面的是权限,r是读取,w是写入,x是执行,3个为1段,第一段代表的是建立这个文件的用户权限,第二段为建立这个文件的用户所属组的权限,第三段为其他用户的权限,哪项为空,则没有这个权限.