1. 程式人生 > >Shell腳本進階練習

Shell腳本進階練習

shell腳本實例練習

1、判斷用戶輸入的數字是否為正整數。


#!/bin/bash

#判斷用戶輸入的參數是否為正整數

read -p "Please input a digit:" int

if [[ "$int" =~ (^[0-9]*[1-9][0-9]*$) ]];then

echo "this digit is positive integer"

else

echo "this digit is not positive integer"

fi

~


2、判斷/var/目錄下的所有文件類型。


#!/bin/bash

for f in /var/* ;do

if [ -L $f ];then

echo "$f is linkfile"

elif [ -f $f ];then

echo "$f is commom fole"

elif [ -d $f ];then

echo "$f is directory"

else

echo "$f is other files"

fi

done


3、計算100以內所有能被3整除的整數之和。


#!/bin/bash

sum=0

for i in {1..100};do

yu=$[i%3]

if [ "$yu" -eq 0 ];then

let sum+=i

fi

done

echo $sum

~


4、

編寫腳本,提示請輸入網絡地址,如192.168.0.0,判斷輸入的網段中主機在線狀態。


#!/bin/bash

> /app/ipv4.log

read -p "Please input the network(eg:192.168.1.0):" network

[[ "$network" =~ ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] || { echo "Please input a legal IP" ; exit 1; }

net=`echo $network | cut -d. -f1-3`

for i in {1..14};do

{

if ping -c1 -w1 $net.$i &>/dev/null;then

echo $net.$i is up |tee -a /app/ipv4.log

else

echo $net.$i is down

fi

}&

done

wait



5、九九乘法表


#!/bin/bash

for i in {1..9};do

for j in `seq 1 $i`;do

echo -e "${j}x${i}=$[j*i]\t\c"

done

echo

done


6、

在/testdir目錄下創建10個html文件,文件名格式為數字N(從1到10)加隨機8個字母,如:1AbCdeFgH.html


#!/bin/bash

for i in {1..3};do

j=`openssl rand -base64 1000 |tr -dc '[alpha]' |head -c8`

touch /app/$i$j.html

done



7、打印等腰三角形


#!/bin/bash

read -p "Please input number:" line

for i in `seq $line`;do

space=`echo $[$line-$i]`

for j in `seq $space`;do

echo -n ' '

done

for k in `seq $[$i*2-1]`;do

echo -n '*'

done

echo

done


Shell腳本進階練習