1、命令替换
当一个命令被包含在一对括号里并在括号前加上符号,如(command),或者被包含在反引号”" (如
command`)中的时候,shell把它替换为这个命令的输出结果。这个过程被称为命令替换。
几个例子:
例1:
[root@localhost root]#pwd
/root/d1
[root@localhost root]# cmd1=pwd
[root@localhost root]# echo “The value of command is: $cmd1.”
The value of command is: pwd
[root@localhost root]# cmd1=$(pwd)
[root@localhost root]# echo “The value of command is: $cmd1.”
The value of comomand is: /root/d1
例2:
[root@localhost root]# echo “The date and time is $(date).”
The date and time is 9月20日 10:23:16 UTC 2011.
2、输入命令read
read命令可以用来读取用户的输入
格式:read [参数] [名称]
<1.> -a :将读入的单词按照空格的划分将其存入数组,索引从0开始
源码:
#!/bin/bash
echo "按照单词的分割放置到数组中,索引从0开始"
read -a variable
echo "第1个:"
echo ${variable[0]}
echo "第2个:"
echo ${variable[1]}
echo "第3个:"
echo ${variable[2]}
echo "第4个:"
echo ${variable[3]}
运行结果:
运行效果:
按照单词的分割放置到数组中,索引从0开始
ew qr34 3qr wer er qw
第1个:
第2个:
ew
第3个:
qr34
第4个:
3qr
<2.>-n:接收指定个数的字符,当达到接收的个术后,立即退出输入状态
源码:
#-n read接收10个字符
echo "-n read接收10个字符"
read -n 10 num
echo
echo "接收的10个字符是:"${num}
运行效果:
-n read接受10个字符
sgfgsngfdf
接收的10个字符是:sgfgsngfdf
<3.>-p : 允许在read命令后直接指定一个提示,并且可以为多个变量赋值
源码:
echo "使用-p参数完成多个变量赋值:"
read -p "请输入三个数字或字符:(用空格隔开)" num1 num2 num3
echo "num1="$num1
echo "num2="$num2
echo "num3="$num3
运行效果:
使用-p参数完成多个变量赋值:
请输入三个数字或字符:(用空格隔开)23 34 345
num1=23
num2=34
num3=345
<4.>-r:不允许反斜线转义任何字符
<5.>-s:不将read输入的数据显示在屏幕上
源码:
#-s read的输入不显示在屏幕上
echo "-s read的输入不显示在屏幕上:"
read -p "password:" -s password
echo
echo "password is "${password}
运行效果:
-s read的输入不显示在屏幕上:
password:
password is 3432 rq erewr w
<6.>-t :read命令等待输入的秒数。当计时满时,回返回一个非0的状态,并且退出等待输入。
源码:
#-t read的输入的等待时间
echo "将会等等待两秒的输入,超时后,会退出等待;返回非0数值"
read -t 2 num
echo ${num}
运行效果:
将会等等待两秒的输入,超时后,会退出等待;返回非0数值
<7.>读取文件中的内容
最后,还可以使用read命令读取Linux系统上的文件。
每次调用read命令都会读取文件中的"一行"文本。当文件没有可读的行时,read命令将以非零状态退出。
读取文件的关键是如何将文本中的数据传送给read命令。
最常用的方法是对文件使用cat命令并通过管道将结果直接传送给包含read命令的 while命令
例子::
#!/bin/bash
count=1 //赋值语句,不加空格
cat test | while read line //cat 命令的输出作为read命令的输入,read读到的值放在line中
do
echo "Line $count:$line"
count=$[ $count + 1 ] //注意中括号中的空格。
done
echo "finish"
exit 0
3、输出命令 echo
格式:echo [参数] [string]
常用参数:
<1.>-n : 输出内容不换行
源码:
#!/bin/bash
echo -n "请输入您的姓名:"
read name
运行结果:
请输入您的姓名:jin
<2.>-e:输出特殊字符的含义,也就是输出字符转义后的意义。
源码:
#-e 输出特殊字符
echo "hello ,\n my name \tis ***"
echo -e "hello ,\n my name \tis ***"
运行效果:
hello ,\n my name \tis ***
hello ,
my name is ***
特殊字符及其作用:
字符 作用
\t 插入tab
\n 换行并且光标移动至行首
\f 换行但光标停留在原来的位置
\b 删除前一个字符
\r 光标移动至行首,但不换行
\\ 插入\字符