shell初级-----处理用户输入

命令行参数

 读取参数

位置参数变量是标准的数字:$0是程序名,$1是第一个参数,$2,是第二个参数,直到第九个参数$9。node

每一个参数必须用空格分开。固然若是要在参数中引用空格必须加引号。shell

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
sum=$[ $1 + $2 ]
echo "first num is $1"
echo "second num is $2"
echo "sum num is $sum"
[root@node1 ljy]# sh ceshi.sh 2 3
first num is 2
second num is 3
sum num is 5

读取脚本名

$0能够获取shell在命令行启动的脚本名bash

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
echo "this script name is $0"
[root@node1 ljy]# sh ceshi.sh 
this script name is ceshi.sh

若是使用另外一些命令执行脚本,可能命令会与脚本名混在一块儿。ide

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
echo "this script name is $0"
[root@node1 ljy]# sh /ljy/ceshi.sh 
this script name is /ljy/ceshi.sh
[root@node1 ljy]# ./ceshi.sh 
this script name is ./ceshi.sh

basename命令能够返回不包含路径的脚本名测试

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
name=$(basename $0)
echo "this script name is $name"
[root@node1 ljy]# sh /ljy/ceshi.sh 
this script name is ceshi.sh
[root@node1 ljy]# ./ceshi.sh 
this script name is ceshi.sh

测试参数

若是你要使用命令行参数,而不当心漏了加,可能就要报错了,this

因此最好加一个测试命令行

-n测试来检查命令行参数是否有数据。blog

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
if [ -n "$1" ] && [ -n "$2" ]
then
   sum=$[ $1 + $2 ]
   echo "first num is $1"
   echo "second num is $2"
   echo "sum num is $sum"
else
   echo "you should identify yourself!"
fi
[root@node1 ljy]# sh ceshi.sh 1 2
first num is 1
second num is 2
sum num is 3
[root@node1 ljy]# sh ceshi.sh 1  
you should identify yourself!

特殊参数变量

参数统计

$#含有脚本运行时携带的命令行参数的个数。能够在脚本中任何地方使用这个变量。ip

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
echo there were $# parameters
[root@node1 ljy]# sh ceshi.sh  1 2 2 3 
there were 4 parameters

if-then语句经常使用-ne来测试命令行参数数量。字符串

抓取全部数据

$*和$@会将命令行提供的全部参数做为一个单词保存。

$@变量会将全部参数当作一个字符串的多个独立的单词。

$*变量会将全部参数当成单个参数。

得到用户输入

基本读取

read命令从标准输入或者另外一个文化描述符中接受输入,收到输入后,read命令会将数据放在一个变量里。

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
echo -n "enter your name:"
read name
echo hello $name
[root@node1 ljy]# sh ceshi.sh 
enter your name:ljy
hello ljy

-n选项不会在字符末尾输出换行符,容许用户紧跟其后的输入数据。

-p命令容许你输入提示符:

超时

使用read命令可能会致使程序一直等待中。

你能够使用-t选项来指定一个定时器。

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
if read -t 5 -p "enter your name:" name
then 
   echo "your name is $name"
else
   echo 
   echo "sorry,slow"
fi
[root@node1 ljy]# sh ceshi.sh 
enter your name:
sorry,slow

隐秘读取

-s选项能够避免输入的内容显示在屏幕上

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
read  -s -p "enter your name:" name
echo
echo "your name is $name"
[root@node1 ljy]# sh ceshi.sh 
enter your name:
your name is ljy

从文件中读取

每次调用一次read命令,都会从文件中读取一行数据,一直到没有内容的时候,read命令会退出并返回非零退出码。

[root@node1 ljy]# more ceshi.sh 
#!/bin/bash
count=1
cat test.txt | while read line
do
  echo line:$line
done
[root@node1 ljy]# sh ceshi.sh 
line:1
line:2
line:3
line:4
line:5
line:

空格也做为一行显示出来了。

相关文章
相关标签/搜索