4-5(shell5-转义、test、函数)

2019-08-22  本文已影响0人  不知名的二狗

转义字符

\b 后退
\n 换行
\t 制表
\ 反斜杠字符
开启转义 -e
不换行 -c

cc@ubuntu:~$ echo "\"hello,world\""
"hello,world"
cc@ubuntu:~$ echo "\\testing\\"
\testing\
cc@ubuntu:~$ echo -e "test\nhello"
test
hello
cc@ubuntu:~$ echo -e "test\bnhello"
tesnhello

read XX 从输入中读取一行

#!/bin/bash
read a
echo $a

第一行的2为终端用户输入

cc@ubuntu:~$ /bin/bash re.sh
2
2

定向符

保存在指定文件(注意此时会覆盖原有内容)

以追加方式保存

cc@ubuntu:~$ echo "hello,world">2.txt
cc@ubuntu:~$ cat 2.txt
hello,world
cc@ubuntu:~$ echo "hello,world">>2.txt
cc@ubuntu:~$ cat 2.txt
hello,world
hello,world

显示命令执行结果
echo `date`

printf

%d 数字
%s 字符串
%c 字符
%f 浮点(%-4.2f 一共4位数,2位小数)

#!/bin/bash
printf "%-10s %-4.2f" cc 273.348494
echo -e "\n"

执行结果

cc@ubuntu:~$ /bin/bash pf.sh
cc         273.35

test命令

-eq 等于为真
-ne 不等于为真
-gt 大于则为真
-ge 小于等于为真

#!/bin/bash
a=20
b=10
if test $a -eq $b
then    
        echo "no"
else    
        echo "yes"
fi   

执行结果

cc@ubuntu:~$ /bin/bash tt.sh
yes

与或非操作符优先级
!(非) > -a(与) > -o(或)

数值运算例子

#!/bin/bash
a=20
b=10
ji=$(($a*$b))
echo $ji

执行结果

cc@ubuntu:~$ /bin/bash sa.sh
200

函数

以下两种方式都可以,$?可以获取返回值

#!/bin/bash
#!/bin/bash
function say(){
        echo "i can say"
}
eat(){
        echo "i can eat"
        return 11
}
say
eat
echo "$?"

执行结果

cc@ubuntu:~$ /bin/bash fun01.sh
i can say
i can eat
11

函数参数

$1 第一个参数
$* 所有参数

#!/bin/bash
fun1(){
echo "$1"
echo "$3"
echo "$*"
}
fun1 11 22 33

执行结果

cc@ubuntu:~$ /bin/bash funcanshu.sh
11
33
11 22 33

递归函数 (可以调用自身的函数)

ctrl+c 可终止运行

上一篇 下一篇

猜你喜欢

热点阅读