首页
学习
活动
专区
工具
TVP
发布

《快学BigData》-Linux 编程(7)

Linux编程1-1)、基本语法

[root@hadoop1 bash]# vi hello

#!/bin/bash

echo "hello world"

[root@hadoop1 bash]# chmod 777 hello

[root@hadoop1 bash]# ./hello

hello world

[root@hadoop1 bash]# sh hello

hello world

1-2)、常用语法A)、If语法

if condition

then

statements

[elif condition

then statements. ..]

[else

statements ]

fi

实例:

[root@hadoop1 bash]# vi ifTest

#!/bin/bash

read -p "please input your name:" NAME

#printf '%s\n' $NAME

if [ $NAME = root ]

then

echo "hello $, welcome !"

elif [ $NAME = **** ]

then

echo "hello $, welcome !"

else

echo "SB, get out here !"

fi

[root@hadoop1 bash]# chmod 777 ifTest

[root@hadoop1 bash]# sh ifTest

please input your name:root

hello root, welcome !

B)、While语法

实例一:

while expression

do

command

done

实例代码一:

[root@hadoop1 log]# while true

> date >> test.log

实例二:

i=1

while ((i

do

echo $i

let i++

done

C)、Case语法

case $1 in

start)

echo "starting"

;;

stop)

echo "stoping"

;;

*)

echo "Usage: "

esac

D)、For语法

方式一:

for N in 1 2 3

do

echo $N

done

for N in 1 2 3; do echo $N; done

for N in ; do echo $N; done

方式二:

for ((i = 0; i

do

echo "welcome $i times"

done

for ((i = 0; i

1-3)、函数A)、函数定义

# func1.sh

hello() ##函数定义

{

echo "Hello there today's date is `date +%Y-%m-%d`"

# return 2 ###返回值其实是状态码,只能在[0-255]范围内

}

echo "now going to the function hello"

hello

# echo $?获取函数的return值

echo "back from the function"

函数调用:

function hello()

或function hello

或hello

B)、函数参数

#!/bin/bash

# fun1.sh

funWithParam(){

echo "第一个参数为$1 !"

echo "第二个参数为$2 !"

echo "第十个参数为$10 !"

echo "第十个参数为$ !"

echo "第十一个参数为$ !"

echo "参数总数有$#个!"

echo "作为一个字符串输出所有参数$* !"

}

funWithParam 1 2 3 4 5 6 7 8 9 34 73

注意,$10不能获取第十个参数,获取第十个参数需要$。当n>=10时,需要使用$来获取参数。

C)、函数返回值

#!/bin/bash

# fun2.sh

funWithReturn(){

echo "这个函数会对输入的两个数字进行相加运算..."

echo "输入第一个数字: "

read aNum

echo "输入第二个数字: "

read anotherNum

echo "两个数字分别为$aNum和$anotherNum !"

return $(($aNum+$anotherNum))

}

funWithReturn

echo "输入的两个数字之和为$? !"

D)、跨脚本调用

存在/root/fun2.sh

可在fun_other.sh中调用apt install htop

#!/bin/bash

# fun_other.sh

. /root/fun2.sh ##注:./之间有空格

#或者source /root/fun2.sh

funWithParam 11 22 33 44 55 66 77 88 99 100 101

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180123G0QM7T00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券