Shell的输出:
Shell的输出有两种常用方法:echo和printf
echo和printf都是标准输出
echo 的用法:
不加参数,
echo 的 -e 参数开启转义;\n 换行 \c 不换行
[root@localhost shell_protest]# sh output.sh
abc\n
abc
abc[root@localhost shell_protest]#
==============Source=========================
[root@localhost shell_protest]# cat output.sh
#!/bin/bash
echo "abc\n"
echo -e "abc\n"
echo -e "abc\c"
printf输出:
printf不自带换行,可以多种格式输出
[root@localhost shell_protest]# sh printf.sh
1 abc
1 abc
abcdefabc
def
a b c
d e f
g h i
j
and 0
--------------------------------
[root@localhost shell_protest]# cat printf.sh
#!/bin/bash
printf "%d %s\n" 1 "abc"
# 没有引号也可以输出
printf '%d %s\n' 1 "abc"
#合并输出了
printf %s abc def
#循环输出,直至参数结束
printf "%s\n" abc def
printf "%s %s %s\n" a b c d e f g h i j
#没有输入时,%s输出是空格,%d输出的是0
printf "%s and %d \n"
Shell的输入:
Shell的输入有两种常见方法:read 和 $参数传递
read的方法:
read方法是从标准输入中获得一个输入,存放到一个标准变量中。
介绍几个常用的参数:
-p(提示语句)
-n(字符个数)
-t(等待时间)
-s(不回显)
-p作用:免去使用echo来提示,直接合成一个指令:
示例:
[root@localhost shell_protest]# sh ./input.sh
input something:nick
hello,nick
[root@localhost shell_protest]# cat input.sh
#!/bin/bash
#shift 1
#echo $1 $2
#echo $0
#echo $#
#echo $*
read -p "input something:" name
echo "hello,$name"
-n:控制输入的有效字数:
[root@localhost shell_protest]# cat input.sh
#!/bin/bash
read -n 5 -p "input something:" name
echo "hello,$name"
[root@localhost shell_protest]# echo aaaaaaaaa|sh ./input.sh
hello,aaaaa
-t:控制超时时间,防止长时间没输入处于阻塞
[root@localhost shell_protest]# sh input.sh
input something:1
hello,1
##!在执行之后没有输入,自动跳过了输入!!
[root@localhost shell_protest]# cat input.sh
#!/bin/bash
read -t 3 na
echo "$na"
read -n 5 -p "input something:" name
echo "hello,$name"
-s:不回显,一般用于密码输入
[root@localhost shell_protest]# sh input.sh
1233
[root@localhost shell_protest]# cat input.sh
#!/bin/bash
read -s na
echo "$na"
参数传递的方法,就是通过执行前,传递参数给程序
用$n(n为自然数,从1~9),举个例子
[root@localhost shell_protest]# cat input.sh
#!/bin/bash
echo $1 $2
[root@localhost shell_protest]# sh ./input.sh aa a
aa a
顺带介绍:
$0是脚本的名字。
$#是传递给脚本或函数的参数个数。
$*是传给脚本的全部参数。
$$当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。
[root@localhost shell_protest]# cat ./input.sh
#!/bin/bash
shift 1
echo $1 $2
echo $0
echo $#
echo $*
----------------------------------------------
[root@localhost shell_protest]# sh ./input.sh aa a
a
./input.sh
1
a
===========================去掉shitf 1后==================
[root@localhost shell_protest]# cat ./input.sh
#!/bin/bash
#shift 1
echo $1 $2
echo $0
echo $#
echo $*
----------------------------------------------------
[root@localhost shell_protest]# sh ./input.sh aa a
aa a
./input.sh
2
aa a
可以观察发现:shift 命令,是对传输参数的移位,把$1的值移到$2。从而影响了$#和$*的输出结果