shell 教程三:echo命令
原创
©著作权归作者所有:来自51CTO博客作者运妙心藏的原创作品,请联系作者获取转载授权,否则将追究法律责任
Shell 的 echo 指令用于字符串的输出。命令格式:
1.显示普通字符串:
这里的双引号完全可以省略,以下命令与上面实例效果一致:
2.显示转义字符
结果将是:
同样,双引号也可以省略
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\"
1. #去掉了双引号,效果与上面的一样
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.sh hello shell!what is your name"It is 1 test""It is 2 test"Liu JingLiu JingMy name is Liu JingXiao Niu
1. #自己从标准输入中输入
Your name is Xiao Niu
4.显示换行
echo -e "OK! \n" # -e 开启转义
echo "It it a test"
输出结果:
5.显示不换行
#!/bin/sh
echo -e "OK! \c" # -e 开启转义 \c 不换行
echo "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.sh hello 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的文件中linux@ubuntu:~/test_shell$ lshello.sh
1. #本身目录下只有一个hello.sh
linux@ubuntu:~/test_shell$ ./hello.sh #执行.shlinux@ubuntu:~/test_shell$ lshello.sh mytest #由于没有mytest文件,自动创建出了一个,并导入打印内容linux@ubuntu:~/test_shell$ cat mytest hello shell! #显示本应在终端输出的内容
7.原样输出字符串,不进行转义或取变量(用单引号)
输出结果:
实例练习:
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.显示命令执行结果
结果将显示当前日期
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.sh Mon Dec 19 21:15:51 PST 2016 #datehello.sh #ls/home/linux/test_shell #pwd
注意点:代码中 ` 是ESC键下面的,那个反单引号,不是和双引号在一起的那个单引号