what?
什么是 shell script(程序化腳本)?其實shell script分為兩個部分一個是shell部分在BASH中就有相應的了解,還有一個部分script「腳本、劇本」的意思。shell script就是針對shell 寫的劇本也就是邏輯等處理。
why?
- 可進行自動化的機器管理的重要依據(jù)
- 追蹤與管理的重要工作
- 進行簡單的入侵檢測功能的使用
- 連續(xù)的單一的指令可以使用循環(huán)解決好
- 簡易的數(shù)據(jù)處理
- 跨平臺支持與學習歷程較短(可使用vi/vim進行編輯)
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、將文件名進行創(chuàng)建
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}
touch ”${file1}“
touch ”${file2}“
touch ”${file3}“
exit 0
數(shù)值簡單計算
簡單的加減乘除運算
可以使用declare來定義變量的類型,bash shell只支持整數(shù)數(shù)據(jù)
#!/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 =$((運算內容))
數(shù)值運算:透過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執(zhí)行方式的差異(source ,sh script ,./script)
直接使用sh .sh或者使用./.sh
執(zhí)行時父程序的bash是不存在的子程序的變量的。
使用source
執(zhí)行時父程序可以拿到變量值