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/bash​​​​​​​​echo "hello shell!"      #显示普通字符串​​​​echo what is your name   #去掉了双引号,效果与上面的一样​​​​echo "\"It is 1 test\""  #显示转义字符​​​​echo \"It is 2 test\"    ​​
1. #去掉了双引号,效果与上面的一样
​​name="Liu Jing" #显示普通自定义变量​​​​echo $name​​​​echo ${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 Jing​​​​Liu Jing​​​​My name is Liu Jing​​​​Xiao Niu​​​​ ​​
1. #自己从标准输入中输入
​​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/bash​​​​​​​​echo -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$ ls​​​​hello.sh                                 #本身目录下只有一个hello.sh​​​​linux@ubuntu:~/test_shell$ cat hello.sh ​​​​#!/bin/bash​​​​​​​​echo "hello shell!" >#把打印的内容重定向到一个名mytest的文件中​​​​​​​​linux@ubuntu:~/test_shell$ ls​​​​hello.sh                                 ​​
1. #本身目录下只有一个hello.sh
​​linux@ubuntu:~/test_shell$ ./hello.sh #执行.sh​​​​linux@ubuntu:~/test_shell$ ls​​​​hello.sh mytest #由于没有mytest文件,自动创建出了一个,并导入打印内容​​​​linux@ubuntu:~/test_shell$ cat mytest ​​​​hello shell! #显示本应在终端输出的内容​​


7.原样输出字符串,不进行转义或取变量(用单引号)

echo '$name\"'

输出结果:

$name\"



实例练习:


​​linux@ubuntu:~/test_shell$ cat hello.sh ​​​​#!/bin/bash​​​​​​​​your_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/bash​​​​​​​​echo `date`​​​​​​​​echo `ls`​​​​​​​​echo `pwd`​​​​linux@ubuntu:~/test_shell$ ./hello.sh ​​​​Mon Dec 19 21:15:51 PST 2016     #date​​​​hello.sh                         #ls​​​​/home/linux/test_shell           #pwd​​

注意点:代码中 ` 是ESC键下面的,那个反单引号,不是和双引号在一起的那个单引号