Shell Script总结

本文介绍Bash脚本的基础操作,包括条件判断、循环结构、函数定义等,并通过实例演示如何进行文件创建、数学运算及网络检测等常见任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于echo

echo -n 不换行输出
echo -e 处理特殊字符 
若字符串中出现以下字符,则特别加以处理,而不会将它当成一般文字输出:
\a 发出警告声;
\b 删除前一个字符;
\c 最后不加上换行符号;
\f 换行但光标仍旧停留在原来的位置;
\n 换行且光标移至行首;
\r 光标移至行首,但不换行;
\t 插入tab;
\v\f相同;
\\ 插入\字符;

显示日期、PATH、用户名、当前路径

#!/bin/bash
#不换行输出
echo -n "date and time is:"
date
#不换行输出
echo -e "date and time is:\c"
date
echo "date and time is:"
date
echo "path is "$PATH
echo -e "your username is:`whoami` \n"
echo -e "your current directory is: \c"
pwd

使用环境变量

#!/bin/bash
my_lang=$LANG
echo $my_lang

要建立三个空的档案,档名最开头由使用者输入决定,假设使用者输入filename 好了, 那今天的日期是 2005/08/23 ,我想要以前天、昨天、今天的日期来建立这个档案,亦即 filename_20050821, filename_20050822, filename_20050823 ,该如何是好?

#!/bin/bash
#Program:
#要建立三个空的档案,档名最开头由使用者输入决定,假设使用者输入filename 好了, 那今天的日期是 2005/08/23 ,我想要以前天、昨天、今天的日期来建立这个档案,亦即 filename_20050821, filename_20050822, filename_20050823 ,该如何是好?
#History:
#2017/12/3  VBird   First release
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 creat 3 files."
read -p "please input the filename what you want:" fileuser

#2.为了避免使用者随意按ENTER,利用变量功能分析文件名是否有设定
filename=${fileuser:-"filename"}

#3.开始利用date指令来取得所需要的当名了
# date --date='+1 days' +%Y%m%d 明天的日期
# date --date='-1 days' +%Y%m%d 昨天的日期
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"
file2="$filename""$date2"
file3="$filename""$date3"

#4.建立文档
touch $file1
touch $file2
touch $file3

实现两数相乘

#!/bin/bash
#要使用者输入两个变量,然后将两个变量的内容相乘, 最后输出相乘的结果,那可以怎么做?
PATH=~/bin
export PATH
echo -e "input 2 numbers and cross them!\n"
read -p "first number:" first
read -p "second number:" second
total=$(($first*$second))
echo -e "\nThe number $first x $second is ==> $total"

if、elif、else

show the user’s choice

#!/bin/bash
#Program:
#   show the user's choice
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "Please input (Y/N):" yn

if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
    echo "ok,continue"
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
    echo "oh,interrupt"
else
    echo "i don't konw what is your choice"
fi

先查看一下 /root/test/logical 这个名称是否存在;

#撰写一支程序,它的作用是:
#先查看一下 /root/test/logical 这个名称是否存在; 
#若不存在,则建立一个档案,使用 touch 来建立,建立完成后离开; 
#如果存在的话,判断该名称是否为档案,若为档案则将之删除后建立一个目录,文件名为 logical ,#之后离开; 
#如果存在的话,而且该名称为目录,则移除此目录!
#!/bin/bash
if [ ! -e /root/test/logical ]; then
touch logical
echo "just make a file logical"
exit 1
elif [ -e logical ] && [ -f logical ]; then
 rm logical 
mkdir logical
echo "remove file and make directory"
exit 1
elif [ -e logical ] && [ -d logical ]; then 
rm -rf logical
echo "remove directory"
exit 1 
else
echo "have nothing"
fi

netstat 的指令

先学一个叫做 netstat 的指令, 这个指令可以查询到目前主机有开启的网络服务端口 (service ports), 利用『 netstat -tuln 』来取得目前主机有启动的服务, 而且取得的信息 为

[root@linux ~]# netstat -tuln  
Active Internet connections (only servers)  
Proto Recv-Q Send-Q Local Address   Foreign Address    State  
tcp        0      0          0.0.0.0:199     0.0.0.0:*          LISTEN  

tcp        0      0           :::80           :::*               LISTEN  

tcp        0      0           :::22           :::*               LISTEN  

tcp        0      0            :::25           :::*               LISTEN 

端口:

* 80: WWW   

* 22: ssh   

* 21: ftp   

* 25: mail  

如何透过 netstat 去侦测我的主机是否有开启这四个主要的网络服务端口呢?

case

#!/bin/bash
#Program:
#   input one,two,three and show on screen
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "this program will print your selection!"
read -p "input your choice:" choice
case $choice in
    "one")
        echo "your choice is ONE"
        ;;
    "two")
        echo "your choice is TWO"
        ;;
    "three")
        echo "your choice is THREE"
        ;;
    *)
        echo "Usage {one|two|three}"
        ;;
esac

for语句

foreach循环

#!/bin/bash
# Program:
#   Using for .... loop to print 3 animals
# History:
# 2015/07/17    VBird   First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

for animal in dog cat elephant
do
    echo "There are ${animal}s.... "
done

用for计算1+2+3+…+100

#!/bin/bsah
#Program:
#    use for to calculate the result '1+2+3+...+100' 


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


echo  "use for to calculate the result '1+2+3+...+100' "
s=0;
for (( i=1; i<=100; i=i+1 ))
do
    s=$(($s+$i))
done
echo "the result is ==> $s"

while

用while计算1+2+3+…+100

#!/bin/bash
#Program:
#   calculate the result "1+2+3+...+100"


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

echo " use while to calculate the result '1+2+3+...+100' "

s=0
i=0
while [ "$i" != "100" ]
do
    i=$(($i+1))
    s=$(($s+$i))
done
echo "the result of '1+2+3+...+100' is ==>$s"

until

#!/bin/bash
#Program:
#   use loop to try find your input.
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "only input yes can stop this program."
read -p "input (YSE/NO):" yn

until [ "$yn" == "yes" ] || [ "$yn" == "YES" ]
do
    read -p "please input yes/YES to stop program:" yn
done
    echo "ok,stopped"

函数

打印选项并转换大小写

#!/bin/bash
#函数的使用
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

function printit(){
echo -n "Your choice is "     # 加上 -n 可以不断行继续在同一行显示
}

echo "This program will print your selection !"
#read -p "please input one||two||three:" choice
case ${1} in 
 "one")
    printit ; echo ${1} | tr 'a-z' 'A-Z'
    ;;
 "two")
    printit ; echo ${1} | tr 'a-z' 'A-Z'
    ;;
 "three")
    printit ; echo ${1} | tr 'a-z' 'A-Z'
    ;;
 *)
    echo "usage ${0} {one|two|three}"
    ;;
esac

带参函数

#!/bin/bash
#带参函数的使用
function printit(){
    echo "Your choice is ${1}"   #这里的参数和下面的不是一回事,
                     #这里的${1}指printit后面的参数(zzz|xxx|mmm|)
}

echo "This program will print your selection !"
case ${1} in			     #这里的${1}指在终端输入时所带的参数
  "one")
    printit zzz  # 請注意, printit 指令後面還有接參數!
    ;;
  "two")
    printit xxx
    ;;
  "three")
    printit mmm
    ;;
  *)
    echo "Usage ${0} {one|two|three}"
    ;;
esac

案例一:分行显示passwd

#!/bin/bash
#Program:
#    我们知道 /etc/passwd 里面以 : 来分隔,第一栏为帐号名称。请写一只程式,可以将 /etc/passwd 的第一栏取出,而且每一栏都以一行字串『The 1 account is "root" 』来显示,那个 1 表示行数。

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

accounts=`cat /etc/passwd | cut -d ':' -f1`
i=0
for account in $accounts
do
#declare -i i=($i+1)
i=$(($i+1))
echo  "The $i account is $account "
done

案例二:计算生日

#!/bin/bash
read -p "please input your birthday(MMDD,ex>0506):" bir
now=`date +%m%d`
if [ "$bir" == "$now" ];then
    echo "happy birthday!!"
elif [ "$bir" -gt "$now" ];then
year=`date +%Y`
total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))
echo "your birthday will be $total_d later"
else
year=$((`date +%Y`+1))
total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))
echo "your birthday will be $total_d later"
fi

检查本地局域网(假定ip:10.0.1.1-10.0.1.200)共200台主机是否与你的主机连通。

#!/bin/bash
#This script check whether the local host connect the host

network="10.0.1.1."
for (( i=1;i<=200;i++ ))
do
ping -c 1 -w 1 ${network}${i} &> /dev/null && result=0 || result=1
if [ $result == 0 ];then
echo "server $network$i is up!"
elif [ $result == 1 ];then
echo "server $network$i is Down!"
fi
done
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值