echo 在linux帮忙文档的形容是显示一行文本,相似于python和java等编程语言中的print语句,实际上它的作用不仅仅如此。能够应用man echo查看具体的参数阐明。

example1: 显示一行文本,任何特殊字符都不会被本义

[root@aliyun-hk1 linux-shell-test]# echo hello\nworld
hellonworld
[root@aliyun-hk1 linux-shell-test]# echo 'hello\nworld'
hello\nworld
[root@aliyun-hk1 linux-shell-test]# echo hello world
hello world
[root@aliyun-hk1 linux-shell-test]#
example2: 显示一行文本,不要输入开端的换行符

[root@aliyun-hk1 linux-shell-test]# echo -n hello world
hello world[root@aliyun-hk1 linux-shell-test]# echo hello world
hello world
example3: 显示一行文本,启用反斜杠前面的转义字符

[root@aliyun-hk1 linux-shell-test]# echo -e 'hello\nworld'
hello
world
[root@aliyun-hk1 linux-shell-test]# echo -e 'hello\tworld'
hello world
example4: 显示一行文本,禁用反斜杠前面的转义字符,echo默认参数

[root@aliyun-hk1 linux-shell-test]# echo -E 'hello\nworld'
hello\nworld
[root@aliyun-hk1 linux-shell-test]# echo -E 'hello\tworld'
hello\tworld
example5: echo与cat的差别比照,echo只用于输入文本,cat用于输入文件内容或者从规范输出中输入

[root@aliyun-hk1 linux-shell-test]# echo hello
hello
[root@aliyun-hk1 linux-shell-test]# cat hello
cat: hello: No such file or directory
[root@aliyun-hk1 linux-shell-test]# echo /etc/hostname
/etc/hostname
[root@aliyun-hk1 linux-shell-test]# cat /etc/hostname
aliyun-hk1
[root@aliyun-hk1 linux-shell-test]# echo hello|cat
hello
[root@aliyun-hk1 linux-shell-test]#
examle6: echo在自动化构建中的作用,例如咱们能够将DB中返回的数据格式化成ansible须要的数据,通过with_lines 传入某个task并循环应用。在某些状况下,从网络、DB等形式获取的规范输入,能够通过echo联合awk和grep等实现后果的格式化或数据荡涤,而后用到后续的脚本中。

[root@aliyun-hk1 linux-shell-test]# echo -en 'name phone addr\nrobin 13712345678 CN\ntom 13812345678 HK\n'
name phone addr
robin 13712345678 CN
tom 13812345678 HK
[root@aliyun-hk1 linux-shell-test]# echo -en 'name phone addr\nrobin 13712345678 CN\ntom 13812345678 HK\n'|awk 'NR>1 {print $1}'
robin
tom

  • name: show the items from DB

    debug:  msg: "{{ item }}"with_lines: "echo -en 'name phone addr\nrobin 13712345678 CN\ntom 13812345678 HK\n'|awk  'NR>1 {print $1}'


    TASK [show the items from DB] ok: [localhost] => (item=robin) => {
    "msg": "robin"
    }
    ok: [localhost] => (item=tom) => {
    "msg": "tom"
    }
    example7: echo还能够将获取到并格式化好的数据写入到一个文件,期待后续应用。

[root@aliyun-hk1 ansible-test]# echo -en 'name phone addr\nrobin 13712345678 CN\ntom 13812345678 HK\n'|awk 'NR>1 {print $1}' > DataFromDB1.txt
[root@aliyun-hk1 ansible-test]# cat DataFromDB1.txt
robin
tom
[root@aliyun-hk1 ansible-test]#
参考链接:
3 ways to use echo command in Linux