echo string
echo "It is a test"
这里的双引号彻底能够省略,如下命令与上面实例效果一致:shell
echo It is a test
echo "\"It is a test\"" #结果将是: #"It is a test"
#!/bin/sh read name echo "$name It is a test"
[root@www ~]# sh test.sh OK #标准输入 OK It is a test #输出
echo -e "OK! \n" # -e 开启转义 echo "It is a test" # 输出结果: # OK! # # It is a test
#!/bin/sh echo -e "OK! \c" # -e 开启转义 \c 不换行 echo "It is a test" # 输出结果: # # OK! It is a test
echo "It is a test" > myfile
echo '$name\"' #输出结果: #$name\"
echo `date` #注意: 这里使用的是反引号 `, 而不是单引号 '。 #结果将显示当前日期 #Thu Jul 24 10:08:46 CST 2014
printf
命令的语法:printf format-string [arguments...]bash
$ echo "Hello, Shell" Hello, Shell $ printf "Hello, Shell\n" Hello, Shell
#!/bin/bash printf "%-10s %-8s %-4s\n" 姓名 性别 体重kg printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234 printf "%-10s %-8s %-4.2f\n" 杨过 男 48.6543 printf "%-10s %-8s %-4.2f\n" 郭芙 女 47.9876
姓名 性别 体重kg 郭靖 男 66.12 杨过 男 48.65 郭芙 女 47.99
更多实例:code
#!/bin/bash # format-string为双引号 printf "%d %s\n" 1 "abc" # 单引号与双引号效果同样 printf '%d %s\n' 1 "abc" # 没有引号也能够输出 printf %s abcdef # 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用 printf %s abc def printf "%s\n" abc def printf "%s %s %s\n" a b c d e f g h i j # 若是没有 arguments,那么 %s 用NULL代替,%d 用 0 代替 printf "%s and %d \n"
执行脚本,输出结果以下所示:orm
1 abc 1 abc abcdefabcdefabc def a b c d e f g h i j and 0
序列 | 说明 |
---|---|
\a | 警告字符,一般为ASCII的BEL字符 |
\b | 后退 |
\c | 抑制(不显示)输出结果中任何结尾的换行字符(只在%b格式指示符控制下的参数字符串中有效),并且,任何留在参数里的字符、任何接下来的参数以及任何留在格式字符串中的字符,都被忽略 |
\f | 换页(formfeed) |
\n | 换行 |
\r | 回车(Carriage return) |
\t | 水平制表符 |
\v | 垂直制表符 |
\\ | 一个字面上的反斜杠字符 |
\ddd | 表示1到3位数八进制值的字符。仅在格式字符串中有效 |
\0ddd | 表示1到3位的八进制值字符 |
$ printf "a string, no processing:<%s>\n" "A\nB" a string, no processing:<A\nB> $ printf "a string, no processing:<%b>\n" "A\nB" a string, no processing:<A B> $ printf "www.runoob.com \a" www.runoob.com $ #不换行