您的位置:首页 > 运维架构 > Shell

Linux学习笔记 - Shell 输出命令

2017-03-01 12:18 288 查看

1. echo 命令

echo 是基本的shell输出命令,她的语法是:

echo string


我们也可以使用她来定制一些输出的格式,具体如下:

输出普通字符串

echo "it is a echo string here!"


PS: 引号可以省略。

显示变量

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

#!/bin/sh
read name
echo "$name It is a test"


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

# sh test.sh
OK                     #标准输入
OK It is a test        #输出


开启转义

echo -e string


示例:

#!/bin/sh

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

结果为:

OK!

It it a test

---

echo -e "OK! \c" # -e 开启转义 \c 不换行
echo "It is a test"

结果为:

OK! It is a test


结果定向至文件

echo "output to a file" > myfile


原样输出 (使用单引号括起来)

#!/bin/bash
echo '$name\ "" '


输出命令执行结果 (使用``括起来)

#!/bin/bash
echo `date`

输出为:

Wed Mar 1 03:40:19 UTC 2017


[b]--我是分割线--[/b]

2. printf 命令

类似C语言的printf函数,语法为:

printf  format-string  [arguments...]


参数说明:

format-string: 为格式控制字符串,例如 %s %c %d %f都是格式替代符

arguments: 为参数列表。

示例:

!bin/bash

# "%d %s\n"为format-string参数, 1为%d的参数, abc为%s的参数
printf "%d %s\n" 1 "abc"

输出:
1 abc


printf的转义序列

序列说明
\a警告字符,通常为ASCII的BEL字符
\b后退
\c抑制(不显示)输出结果中任何结尾的换行字符(只在%b格式指示符控制下的参数字符串中有效),而且,任何留在参数里的字符、任何接下来的参数以及任何留在格式字符串中的字符,都被忽略
\f换页(formfeed)
\n换行
\r回车(Carriage return)
\t水平制表符
\v垂直制表符
\\一个字面上的反斜杠字符
\ddd表示1到3位数八进制值的字符。仅在格式字符串中有效
\0ddd表示1到3位的八进制值字符
实例:

#example1
$ printf "a string, no processing:<%s>\n" "A\nB"
a string, no processing:<A\nB>

#example2
$ printf "a string, no processing:<%b>\n" "A\nB"
a string, no processing:<A
B>

#example3
$ printf "www.cnblog.com \a"
www.cnblog.com $                  #不换行


以上就是shell的两种输出命令的简介 :)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: