10. Shell echo命令

Shell echo命令

Shell 的 echo 指令与 PHP 的 echo 指令类似,都是用于字符串的输出。命令格式:

1.echo string

您可以使用echo实现更复杂的输出格式控制。

1.显示普通字符串:

1.echo "It is a test"

这里的双引号完全可以省略,以下命令与上面实例效果一致:

1.echo It is a test

2.显示转义字符

1.echo "\"It is a test\""

结果将是:

1."It is a test"

同样,双引号也可以省略

3.显示变量

read 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量

1.#!/bin/sh
2.read name 
3.echo "$name It is a test"

以上代码保存为 test.sh,name 接收标准输入的变量,结果将是:

1.[root@www ~]# sh test.sh
2.OK                     #标准输入
3.OK It is a test        #输出

实践

1.#!/bin/bash
2.read name
3.echo '$name it is test'

输出

1.[root@localhost lcr]# ./helloworld.sh 
2.ok
3.$name it is test

不显示变量,因为使用的是单引号 修改如下

1.#!/bin/bash
2.read name
3.echo "$name it is test"

输出结果

1.[root@localhost lcr]# ./helloworld.sh 
2.haha
3.haha it is test

结论:尽量使用双引号,除非特别需要

4.显示换行

1.echo -e "OK! \n" # -e 开启转义
2.echo "It it a test"

输出结果:

1.OK!
2.
3.It it a test

5.显示不换行

1.#!/bin/sh
2.echo -e "OK! \c" # -e 开启转义 \c 不换行
3.echo "It is a test"

输出结果:

1.OK! It is a test

6.显示结果定向至文件

1.echo "It is a test" > myfile
1.[root@localhost lcr]# ./helloworld.sh
2.[root@localhost lcr]# ls
3.helloworld.sh            myfile  公共  视频  文档  音乐
4.mediawiki-1.29.0.tar.gz  perl5   模板  图片  下载  桌面
5.
6.[root@localhost lcr]# vim myfile 
Alt text

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

1.echo '$name\"'

输出结果:

1.$name\"

8.显示命令执行结果

1.echo `date`

注意: 这里使用的是反引号 `, 而不是单引号 ‘。

结果将显示当前日期

1.Thu Jul 24 10:08:46 CST 2014

反引号就是tab键上面那个

实践

1.[root@localhost lcr]# ./helloworld.sh
2.2017年 09月 15日 星期五 00:47:32 CST

Last updated

Was this helpful?