Linux学习笔记

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! 
" # -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

--我是分割线--

2. printf 命令

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

printf  format-string  [arguments...]

参数说明:

  • format-string: 为格式控制字符串,例如 %s %c %d %f都是格式替代符
  • arguments: 为参数列表。

示例:

!bin/bash

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

输出:
1 abc

printf的转义序列

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

实例:

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

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

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

以上就是shell的两种输出命令的简介 :)

原文地址:https://www.cnblogs.com/atuotuo/p/6483664.html