美文网首页
linux命令(三)

linux命令(三)

作者: 墨线宝 | 来源:发表于2019-10-01 22:04 被阅读0次

读取变量

使用read来读取用户的输入变量

image

首先先用一个简单的例子,来看一下read的使用

#!/bin/bash
read -p "please input your name:" name
echo "name is $name"
exit 0
image
对于多个参数,read以空格来分隔

对于密码等不想将输入的内容显示出来,可以read -s

#!/bin/bash
read -p "please input your name: " name \n
echo "name is $name"
read -s -p "please input your password: " password
echo "password is $password"
exit 0
image

注意:

  • 如果输入的数据数量少于变量的个数,那么多余的变量不会获取到数据,即变量值为空。
  • 如果输入的数据数量多余变量的个数,那么超出的数据将都赋值给最后一个变量。

使用read读取文件
每次调用read命令都会读取文件中的"一行"文本。当文件没有可读的行时,read命令将以非零状态退出。

#!/bin/bash
count=0
while read line //read 读到的值会放到line中
do
let count=$count+1
echo "Line $count:$line"
done<test.txt //读取test.txt文件
echo "finished"
echo "Line is $count"
exit 0

上一节 linux命令(二) 环境变量              下一节 linux命令(四) 操作文件

相关文章

网友评论

      本文标题:linux命令(三)

      本文链接:https://www.haomeiwen.com/subject/xlhlpctx.html