1、简单范例
<1>对谈式脚本:变量内容由用户决定
[hadoop1@hadoop bin]$ vim showname.sh
#!/bin/bash
#program:
# user inputs his first name and last name .program show his full name
#history
# 2018.10.9 lile first release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/locale/bin:/usr/locale/sbin:~/bin
export PATH
read -p "please input your first name : " firstname
read -p "please input your last name : " lastname
echo -e "\nyour full name is :${firstname} ${lastname}"
上述指令的作用是输入名和字,输出全名
<2>随日期变化:利用data进行文件的建立
#!/bin/bash
#program
#program creates three files ,which named by user's input and date command.
#history
# 2018.10.9 lile first release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/locale/bin:/usr/locale/sbin:~/tempture
export PATH
echo -e "I will use touch command to create 3 files" #直接打印
read -p "please input your filename:" fileuser #使用者输入文件名
filename=${fileuser:-"filename"}
date1=$(date --date='2 days ago' +%Y%m%d) #按照date格式显示时间,前两天的时间
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)
file1=${filename}${date1} #配置文件名,其格式可以进行更改${}为引用变量
file2=${filename}${date2}
file4=${filename}${date3}
touch ${file1} #利用touch建立档名
touch ${file2}
touch ${file3}
当输入文件档名为lile时,最后建立的文件为 lile20181007 lile20181008 lile0181009
<3>数值运算:简单的加减乘除
我们可以使用declare来定义变量类型,当定义变量为整数时才可以进行加减运算,此外我们可以利用 $(计算式) 的格式进行数值的运算。在bash shell中预设仅支持整数数据。
#!/bin/bash
#program
# user inputs 2 integer number;program will cross these two numbers
#history
# 20181009 lile first release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/locale/bin:/usr/locale/sbin:~/tempture
export PATH
echo -e "you should input 2 numbers ,I will multiplying them \n"
read -p "first number : " f
read -p "second number : " s
total=$((${f}*${s})) #注意该行的格式
echo -e "${total}"
在数值运算上,我们可以使用 $ declare -i total=${firstnumber} * ${secondmunber}
建议使用,命令:$ 变量=$((运算内容))
<4>数值运算:透过bc计算pi
在计算pi时,小数点以下位数可以无限制的延伸下去,而bc有提供运算pi的函数式,使用该函数式需要使用bc -l来呼叫
#!/bin/bash
#progaram
# user input a scale number to calculate pi number
#history
# 20181010 lile first release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/locale/bin:/usr/locale/sbin:~/temp
export PATH
echo -e "this program will calculate pi value.\n"
echo -e "you should input a float number to calculate pi value.\n"
read -p "this scale number is :" checking
num=${checking:-"10"}
echo -e "starting calculate pi value .be patient"
time echo "scale=${num};4*a(1)" | bc -lq ##4*a(1)为bc提供的一个函数,scale是为了计算小数
##点位数
2、scripts 的执行方式差异(source,sh scripts ,./scripts)
<1>利用直接执行的方式来执行script
上述中提到的直接下达指令(不论是绝对路径/相对路径还是PATH内),或者利用bash或sh来下达脚本时,该script都会使用新的bash环境来执行脚本命令,实质就是script是在子程序的bash中执行。在子程序运行完成后,在子程序内的各项变量或动作将会结束而不会回传到父程序中。
<2>利用source来执行脚本:在父程序中执行
当我们执行脚本文件时使用source命令来下达指令时,在父程序bash环境下执行。
命令 :$ source script文件 ##在父程序中执行,当下达命令 echo {script中的变量} 会产生数据,script的各项动作在原本的bash内生效,当不注销系统,而让某些写入的~/.bashrc 的设定生效,需要使用 source ~/.bashrc 而不能使用 bash ~/.bashrc。