Shell入门:Shell函数及file重定向,shell重定向
Shell入门:Shell函数及file重定向,shell重定向
Shell入门(五)之Shell函数和file重定向
Shell函数
Shell函数定义:
[ function ] funname [()] { action; [return int;] }
说明
可以使用function fun()定义,也可以直接使用fun()定义,不带任何参数。 参数返回,可以使用return返回,如果不加,将以最后一条命令运行结果,作为返回值。eg1: 简单的函数
定义fun1.sh文件
#!/bin/bash echoFun(){ echo "hello world" } echo "fun start" echoFun echo "fun end"
执行fun1.sh文件
./fun1.sh
输出:
fun start hello world fun end
eg2: return的函数
定义文件fun2.sh
#!/bin/bash returnFun(){ echo "input first num:" read firstNum echo "input second num:" read secondNum return $[ firstNum + secondNum ] } returnFun echo "$firstNum + $secondNum = $?"
输出:
[root@localhost zhang]# ./fun2.sh input first num: 10 input second num: 20 10 + 20 = 30
函数参数
在Shell中,调用函数时可以向其传递参数。在函数体内部,通过$n的形式来获取参数的值,例如:$1表示第一个参数,$2表示第二个参数。
eg:
#!/bin/bash paramFun(){ echo "param1 : $1" echo "param2 : $2" echo "param4 : $4" echo "param10 : $10" echo "param10 : ${10}" echo "param count : $#" echo "param all : $*" } paramFun 1 2 4 8 16 32 64 128 256 512 1024
输出结果:
param1 : 1 param2 : 2 param4 : 8 param10 : 10 param10 : 512 param count : 11 param all : 1 2 4 8 16 32 64 128 256 512 1024
注意:$10不能获取第10个参数,获取第10个参数需要${10}。当$n中的n>=10时,需要使用{n}来获取参数。
函数参数:
参数处理 | 说明 |
---|---|
$# | 传递到脚本的参数的个数 |
$* | 以一个单字符串显示所向脚本传递的参数 |
$$ | 脚本运行的当前进程ID号 |
$! | 后台运行的最后一个进程的ID号 |
$@ | 与$*相同,但是使用时加引导号,并在引导中返回每个参数 |
$- | 显示Shell使用当前选项,与set命令功能相同 |
$? | 显示最后命令的退出状态。0表示没有错误,其他任何值表示有错误。 |
Shell输入/输出重定向
重定向命令列表如下:
命令 | 说明 |
---|---|
command > file | 将输出重定向到file |
command < file | 将输入重定向到file |
command >> file | 将输出以追加的方式重定向到file |
n> file | 将文件描述符为n的文件重定向到file |
n>> file | 将文件描述符为n的文件以追加的方式重定向到file |
n>& m | 将输出文件m和n合并 |
n<& m | 将输入文件m和n合并 |
<< tag | 将开始标记tag和结束标记tag之间的内容作为输入 |
注意:文件描述符0,通常是标准输入,1是标准输出,2是标准错误输出
eg1: 输出重定向command1 > file
[root@localhost zhang]# echo "hello world" > file1.txt [root@localhost zhang]# cat file1.txt hello world
eg2: 输出以追加的方式,command >> file
[root@localhost zhang]# echo "---shell---" >> file1.txt [root@localhost zhang]# cat file1.txt hello world ---shell---
eg3: 输入重定向,command < file
[root@localhost zhang]# cat < file1.txt hello world ---shell---
eg4: 文件描述符输出,n> file && n>> file
文件描述符分为:0,1,2
- 0:标准输入
- 1:标准输出
- 2:标准错误输出
eg:
1> file && 1>> file[root@localhost zhang]# echo "abc" 1> file2.txt [root@localhost zhang]# cat file2.txt abc [root@localhost zhang]# echo "def" 1>> file2.txt [root@localhost zhang]# cat file2.txt abc def2> file&&2>> file
[root@localhost zhang]# echo "error" 2> file2.txt error [root@localhost zhang]# cat file2.txt [root@localhost zhang]# echo "error 2" 2>> file2.txt error 2 [root@localhost zhang]# cat file2.txt [root@localhost zhang]#
eg: << tag
#!/bin/bash cat << --- abcdefg hijklmn opqrst uvwxyz ---
输出结果:
[root@localhost zhang]# ./file4.sh abcdefg hijklmn opqrst uvwxyz
评论暂时关闭