shell 7echo命令

时间:2023-03-08 22:24:44

1. echo

echo用于字符串的输出

1.1. 显示普通字符串

#!/bin/sh
echo "Hello world" #Hello world
echo Hello world #Hello world

1.2. 显示转译字符

#!/bin/sh
echo "\"Hello world\"" #"Hello world"
echo "Hello\tworld" #Hello world
echo "Hello\nworld" #Hello<br>world

1.3. 使用双引号显示变量,使用单引号原样输出

#!/bin/sh
name="cup"
echo "this is ${cup}" #this is
echo 'this is ${cup}' #this is ${cup}

1.4. 显示结果定向至文件

#!/bin/sh
echo start #start
echo "OK! \c" > a.txt
echo "It is a test" >> a.txt
echo cat a.txt #cat a.txt
cat a.txt #OK! It is a test
echo rm file #rm file
rm -rf a.txt

1.5. 显示命令执行结果

#!/bin/sh
echo `date` #2018年 9月 2日 星期日 23时54分45秒 CST

1.6. Mac中-e参数只在命令行可用,脚本中会当作普通字符串处理

\a 发出警告声
\b 删除前一个字符
\c 最后不加上换行符号
\f
\v 与\f相同
换行但光标仍旧停留在原来的位置
\n 换行且光标移至行首
\r 光标移至行首,但不换行
\t 插入tab
\ 插入\字符
\nnn 插入nnn(八进制)所代表的ASCII字符

shell 7echo命令

2.printf

printf使用引用文本或空格分隔的参数,外面可以在printf中使用格式化字符串,还可以指定字符串的宽度、左右对其方式等。printf不会像echo自动添加换行符,因此需要手动添加换行符\n

语法:

printf format-string [arguments...]
# format-string:为格式控制字符串
# arguments:参数列表

常用字符:

  • %s 字符串
  • %d,%i 十进制整数
  • %c ASCII字符。显示相对应参数的第一个字符
  • %e,%E,%f 浮点格式
  • %g %E或%f转换,看哪一个较短,则删除结尾的0
  • %G %E或%f转换,看哪一个较短,则删除结尾的0
  • \b 后退 \f 换页 \n 换行 \r 回车 \t 水平制表符 - 左对齐

更多参考http://man.linuxde.net/printf,http://www.runoob.com/linux/linux-shell-printf.html

#!/bin/sh
#打印普通字符串
printf "hello\t"
printf "world\n"
#打印格式化字符串
printf "%-10s %-8s %-10s %-4s\n" 姓名 性别 绰号 排名
printf "%-10s %-8s %-10s %-4d\n" 宋江 男 及时雨 1
printf "%-10s %-8s %-10s %-4d\n" 吴用 男 智多星 3
printf "%-11s %-8s %-10s %-4d\n" 卢俊义 男 玉麒麟 2

shell 7echo命令

%-10s 宽度为10的字符串(-表示左对齐,没有则表示右对齐),任何字符都会被显示在10个字符款的字符内,如果不足则自动以空格填充,超过也会将内容全部显示出来。

#!/bin/sh
printf "%-10s %-5s\n" "hello" "apache tomcat"
printf "%10s %5s\n" "world" "apache tomcat"

shell 7echo命令

#!/bin/sh
#双引号
printf "%d %s\n" 1 "abc"
#单引号和双引号一样
printf '%d %s\n' 1 "abc"
#没有引号也可以输出
printf %s abcefg
echo "****"
#格式只指定了一个参数,但多出的参数仍然可以按照该格式输出
printf %s abc def
echo "****"
printf "%s \n" abc def
printf "%s %s %s \n" a b c d e f g h i j
#如果没有参数,s用null代替,d用0代替
printf "%s and %d \n"

shell 7echo命令

3.read

read命令用于从键盘或文件中读入信息,可同时给多个变量赋值。如果输入的值的个数多余变量个数,多余的值会赋值给最后一个变量

read [-option] 变量列表

常用参数:

  • -p 字符串:用于在请求输入之前给出提示信息
#!/bin/bash
read name
echo "name:${name}"
read -p "please input your name:" yourname
echo "yourname:${yourname}"
read -p "please input classmates:" test1 test2 test3
echo "test1:${test1} test2:${test2} test3:${test3}"

shell 7echo命令

4.tee

表示将输出的内容同时输出到到指定的文件内,如果想看到输出的同时,把输出也同时考入一个文件,适用tee。经常和管道符号|一起使用

tee [-option] 文件名

常用参数:

  • -a:将输出的内容追加到指定的文件内容末尾(不覆盖文件原有内容)
ps -ef|tee proc.info