The file descriptor is an integer associated with the file input and output. It is used to track files that have already been opened. The most common file descriptors are stdin, stdout, stderr. We can even redirect the contents of a file description to another file descriptor. The file descriptor 0,1,2 is reserved by the system:
0----stdin (standard input) 1----stdout (standard output) 2----stderr (standard error)
Instance
(i), redirect the output text to a file:
[[email protected] shell]# echo "This is a example test" > Temp.txtyou has new mail in/var/spool/mail/root[[email prot Ected] shell]# cat tempcat:temp: No file or directory [[email protected] shell]# Cat Temp.txtthis is a example test[[email protected] shell]# Echo This was a example test> Temp.txt[[email protected] shell]# cat Temp.txtthis is a example test[[email prot Ected] shell]# Echo ' This was a example test ' > Temp.txt[[email protected] shell]# cat Temp.txtthis is a example test
(ii) Append text to the target file
[[email protected] shell]# echo ' This was a example test ' >> temp.txt[[email protected] shell]# cat Temp.txtthis is a Example Testthis is a example test[[email protected] shell]# echo This is a example test>> temp.txt[[email protected ] shell]# Cat Temp.txtthis is a example testthis are a example testthis is a example test
(iii), CAT file name: View the contents of a file
(d), standard error redirection, when the command output error message, stderr information will be printed out
[[email protected] shell]# ls +ls: Cannot access +: No file or directory [[email protected] shell]# echo $?2[[email protected] shell]# ls + ; OUT.TXTLS: Unable to access +: No file or directory [[email protected] shell]# ls + 2> out.txt[[email protected] shell]# cat OUT.TXTLS: Cannot access +: No file or directory
The first LS + in + is an illegal parameter, so the command will fail to execute;
echo $? Can output the last command after the state of execution;
The third sentence of LS + >out.txt will execute the failed information output to the screen, not the file, the last sentence plus the file description characters output to the file, and then you can see the contents of the file;
(v), customization file descriptor
Create file descriptor for file reading;
[Email protected] shell]# echo This is S test > Input.txt[[email protected] shell]# exec 3< Input.txt[[email protect Ed] shell]# Cat &3[1] 8171bash:3: Command not found[[email protected] shell]# cat 3cat:3: No file or directory [1]+ stopped< C1/>cat[[email protected] shell]# cat <&3this is s test
Shell file descriptors and redirects