shell Script入门

2021-07-19  本文已影响0人  一萍之春

what?

什么是 shell script(程序化脚本)?其实shell script分为两个部分一个是shell部分在BASH中就有相应的了解,还有一个部分script「脚本、剧本」的意思。shell script就是针对shell 写的剧本也就是逻辑等处理。

why?

How

script编写的注意事项.png script的文件件地址处理.png

shell script的编写习惯

script的编写习惯.png

第一个script(Hello)

#!/bin/bash
#Program:
# This is "Hello World"
#History:
#2021/07/.19
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo -e "Hello World! \a \n"
exit 0

通过用户的键盘输入

#!/bin/bash
#program:
# User inputs his first name and last name .Program shows his full name
#Hiustory:
#2021/07/19
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "'please input your first name:" firstname
read -p "\nplease input your last name:" lastname
echo -e "\nyour full name :" ${firstname} ${lastname}
exit 0

通过时间的变化:利用date进行文件的建立

!/bin/bash
#Program:
# Program creates 3 files ,which named by user input and date command
#history 
# 2021/07/19
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#1、让用户自己输入文件名,并获得fileuser变量
echo -e "I will use 'touch' command to 3 files"
read -p "Please input your filename:" fileuser
#2、为了避免用户直接按enter对变量fileuser进行判断是否有进行赋值
filename=${fileuser:-"filename"}
#3、开始使用date指令来获取所需要的文件名
date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)
file1=${filename}${date1}
#4、将文件名进行创建
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}
touch ”${file1}“
touch ”${file2}“
touch ”${file3}“
exit 0

数值简单计算

简单的加减乘除运算
可以使用declare来定义变量的类型,bash shell只支持整数数据

#!/bin/bash
#Program :
#User input 2 integer numbers;program will cross these two numbers.
#history:
#2021/07/19
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e "You should input 2 number ,I will mutiplying them!\n"
read -p "first number:" fristnum
read -p "second numsber: " secondnum
total=$((${fristnum}*${secondnum}))
echo -e "\nThe result of ${fristnum}X${secondnum}is==>${total}"
#也可以使用
declare -i total=${fristnum}*${secondnum}
echo -e "\nThe result of ${fristnum}X${secondnum}is==>${total}"

推荐使用 var =$((运算内容))

数值运算:透过bc计算pi

#!/bin/bash
#Program :
#  User input a scale number to calculkate pi number.
#history:
#2021/07/19
#User:Thomas

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo -e "This prporam will calulate pi value.\n"
echo -e "you should input a float number to calculate pi value.\n"
read -p "The scale number (10~10000)?" checking
num=${checking:-"10"}
echo -e 'Starting calcuate pi value.Be patinent.'
time echo "scale=${num};4*a(1)" | bc -lq 

script执行方式的差异(source ,sh script ,./script)

直接使用sh .sh或者使用./.sh

执行时父程序的bash是不存在的子程序的变量的。

使用source

执行时父程序可以拿到变量值

上一篇下一篇

猜你喜欢

热点阅读