您的位置:首页 > 大数据

Spark修炼之道(基础篇)——Linux大数据开发基础:第十四节:Shell编程入门(六)

2015-10-06 16:13 731 查看

本文主要内容

case控制结构

read命令

管道

1. case控制结构

参考:http://blog.csdn.net/dreamtdp/article/details/8048720

case控制结构语法格式:

case expression  in
pattern1  )
statements ;;
pattern2  )
statements ;;
...
esac


case控制结构较之于if条件判断,代码可读性更强,典型的应用场景是:编写的shell Script可能会跨越好几种平台,如Linux、FreeBSD、Solaris等等,而各平台之间,多多少少都有不同之处,有时候需要判断目前正在那一种平台上执行。此时可以利用uname命令与case控制结构搭配使用,具体代码如下:

root@sparkslave02:~/ShellLearning/Chapter14# vim case01.sh
#!/bin/sh

#uname -s获取linux系统内核
SYSTEM=`uname -s`

case $SYSTEM in
Linux)
echo "My system is Linux"
echo "Do Linux stuff here..."
;;
FreeBSD)
echo "My system is FreeBSD"
echo "Do FreeBSD stuff here..."
;;
*)
echo "Unknown system : $SYSTEM"
echo "I don't what to do..."
;;
#case的反拼写法
esac

root@sparkslave02:~/ShellLearning/Chapter14# chmod a+x case01.sh
root@sparkslave02:~/ShellLearning/Chapter14# ./case01.sh
My system is Linux
Do Linux stuff here...


2. read命令

read命令在shell脚本中很重要,学用这个命令来接受用户输入,直接上代码演示它的使用方法:

root@sparkslave02:~/ShellLearning/Chapter14# vim read.sh
#! /bin/bash
#-p(prompt) 选项表示,输出提示,本例中会输出"pleas input a number:",提示用输入
read -p "pleas input a number:" num[敲回车]
echo "the input number is $num"

root@sparkslave02:~/ShellLearning/Chapter14# chmod a+x read.sh

root@sparkslave02:~/ShellLearning/Chapter14# ./read.sh
pleas input a number:12
the input number is 12


上面给出的代码在输完12后,敲回车后脚本将继续运行,对变量num输出。read命令还有一种用法是,当输出的字符满n个后脚本继续运行,具体使用如下:

root@sparkslave02:~/ShellLearning/Chapter14# vim read.sh
#! /bin/bash
#-n 4 选项表示,输入满4个字符后,接着执行后面的脚本
read -p "please input:" -n 4 num
echo "the input is $num"

root@sparkslave02:~/ShellLearning/Chapter14# vim read02.sh
root@sparkslave02:~/ShellLearning/Chapter14# chmod a+x read02.sh
root@sparkslave02:~/ShellLearning/Chapter14# ./read02.sh
please input:readthe input is read


有时候我们要输入密码等敏感字符,此时可以使用-s 选项,具体使用代码如下:

#! /bin/bash
#-s(secret) 选项,输入时不会显示在终端
read -p "pleas input the passwd:" -s password
echo "the input passwd is $password"


还有一种常用的用法是超时未输入则继续运行脚本,未输入的变量可以用默认的值

#! /bin/bash
#-t 2 表示两秒后未输入,则继续运行剩余脚本
read -t 2 inputStr
echo $inputStr


3. 管道

管理在linux操作系统中是一个非常重要的概念,在实际使用中使用非常广泛,管理命令的格式如下:

cmd1 | cmd2 | cmd3


指的是cmd1的输出作为cmd2的输入,cmd2的输出又作为cmd3 的输入,如此串起来很像一个管道(pipe),例如下面这个命令常用来查看ssh服务是否启动:

//ps -e命令得到的进程信息输出作为 grep命令的输入,过滤出包含ssh的进程信息
root@sparkslave02:~/ShellLearning/Chapter14# ps -e | grep ssh
1673 ?        00:00:00 sshd
1794 ?        00:00:00 ssh-agent
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  大数据 shell 编程