输出带有转义字符的内容
单独一个echo表示一个换行
使用echo输出时,每一条命令之后,都默认加一个换行;要想取消默认的换行,需要加 -n 参数。
1 2 3 4 5 6 7 | #!/bin/bash #文件名:test.sh echo "aaaaaaaaaaa" echo "bbbbbbbbbbb" echo -n "ccccccccccc" echo "ddddddddddd" |
运行脚本:
1 2 3 4 5 | ubuntu@ubuntu:~$ . /test .sh aaaaaaaaaaa bbbbbbbbbbb cccccccccccddddddddddd ubuntu@ubuntu:~$ |
使用双引号括起来的内容中有转义字符时,在添加参数 -e 之后才会被转义,否则会原样输出。
1 2 3 4 5 | #!/bin/bash #文件名:test.sh echo "hello\n world" echo -e "hello\n world" |
运行脚本:
1 2 3 4 5 | ubuntu@ubuntu:~$ . /test .sh hello\n world hello world ubuntu@ubuntu:~$ |
读取用户输入:
方式一:
1 2 3 4 5 6 | #!/bin/bash #文件名:test.sh echo -n "please input your name and age:" read name age echo "welcome $name, your age is $age" |
方式二:
1 2 3 4 5 | #!/bin/bash #文件名:test.sh read -p "please input your name and age:" name age echo "welcome $name, your age is $age" |
读入的内容会自动保存到变量中去,可以直接使用变量获取输入的值。
执行上面两个脚本,结果都为:
1 2 3 4 | ubuntu@ubuntu:~$ . /test .sh please input your name:beyond 10 welcome beyond, your age is 10 ubuntu@ubuntu:~$ |
改变字体颜色:
以 \e[前景颜色;背景颜色m 开头,中间为内容,然后以 \e[0m结束,0m表示将颜色恢复为默认的颜色,如果不加0m,则之后的所有输出都将使用前面的设置。
其中使用字母m来分隔转义字符和内容。同时输出的时候,因为有转义字符,所以要加-e参数
\e可以使用八进制的\033代替。
颜色表:
字体颜色 | 黑30 | 红31 | 绿32 | 棕33 | 蓝34 | 紫35 | 青36 | 白37 |
背景颜色 | 黑40 | 红41 | 绿42 | 棕43 | 蓝44 | 紫45 | 青46 | 白47 |
1 2 3 4 5 6 7 8 | #!/bin/bash #文件名:test.sh echo -e "\e[32;40m this is test \e[0m" ; echo -e "\e[33;47m this is test \e[0m" ; echo -e "\033[32;40m hello world \033[0m" ; echo -e "\033[33;47m hello world \033[0m" ; |
运行结果:
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWFnZXMyMDE3LmNuYmxvZ3MuY29tL2Jsb2cvODQ4ODgwLzIwMTgwMS84NDg4ODAtMjAxODAxMDgxNTM2MDYzNjMtMjEwMTI3MjQ2LnBuZw)