本文主要是介绍shell 教程三:echo命令,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Shell 的 echo 指令用于字符串的输出。命令格式:echo 一个字符串
1.显示普通字符串:
echo "It is a test"
这里的双引号完全可以省略,以下命令与上面实例效果一致:
echo It is a test
2.显示转义字符
echo "\"It is a test\""
结果将是:
"It is a test" 同样,双引号也可以省略
3.显示变量
read 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量
关于知识点1, 知识点 2, 知识点 3实例:
linux@ubuntu:~/test_shell$ cat hello.sh#!/bin/bashecho "hello shell!" #显示普通字符串echo what is your name #去掉了双引号,效果与上面的一样echo "\"It is 1 test\"" #显示转义字符echo \"It is 2 test\"#去掉了双引号,效果与上面的一样name="Liu Jing" #显示普通自定义变量echo $nameecho ${name}echo "My name is ${name}"read your_name #从标准输入中读取一行echo "Your name is ${your_name}" #输出读取到的内容
linux@ubuntu:~/test_shell$ ./hello.shhello shell!what is your name"It is 1 test""It is 2 test"Liu JingLiu JingMy name is Liu JingXiao Niu#自己从标准输入中输入Your name is Xiao Niu
4.显示换行
echo -e "OK! \n" # -e 开启转义 echo "It it a test"
输出结果:
OK!It it a test
5.显示不换行
#!/bin/sh echo -e "OK! \c" # -e 开启转义 \c 不换行 echo "It is a test"
输出结果:
OK! It is a test
实例练习:
linux@ubuntu:~/test_shell$ cat hello.sh#!/bin/bashecho -e "hello shell!\n"echo "end1"echo -e "hello shell!\c"echo "end2"linux@ubuntu:~/test_shell$ ./hello.shhello shell!end1 #第11行为\n导致的hello shell!end2 #第13行里的\c取消了echo本身的换行
6.显示结果定向至文件
echo "It is a test" > myfile
实例练习:
linux@ubuntu:~/test_shell$ lshello.sh #本身目录下只有一个hello.shlinux@ubuntu:~/test_shell$ cat hello.sh#!/bin/bashecho "hello shell!" > mytest #把打印的内容重定向到一个名mytest的文件中linux@ubuntu:~/test_shell$ lshello.sh#本身目录下只有一个hello.shlinux@ubuntu:~/test_shell$ ./hello.sh #执行.shlinux@ubuntu:~/test_shell$ lshello.sh mytest #由于没有mytest文件,自动创建出了一个,并导入打印内容linux@ubuntu:~/test_shell$ cat mytesthello shell! #显示本应在终端输出的内容
7.原样输出字符串,不进行转义或取变量(用单引号)
echo '$name\"'
输出结果:
$name\" 实例练习:
linux@ubuntu:~/test_shell$ cat hello.sh#!/bin/bashyour_name="hello shell"echo '$your_name'echo '${your_name}'linux@ubuntu:~/test_shell$ ./hello.sh$your_name${your_name}
8.显示命令执行结果
echo `date`
结果将显示当前日期
Thu Jul 24 10:08:46 CST 2014
linux@ubuntu:~/test_shell$ cat hello.sh#!/bin/bashecho `date`echo `ls`echo `pwd`linux@ubuntu:~/test_shell$ ./hello.shMon Dec 19 21:15:51 PST 2016 #datehello.sh #ls/home/linux/test_shell #pwd
注意点:代码中 ` 是ESC键下面的,那个反单引号,不是和双引号在一起的那个单引号
这篇关于shell 教程三:echo命令的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!