Shell脚本常用示例
While 循环
#!/bin/bash
i=0
while [ $i -le 2 ]
do
echo Number: $i
((i++))
done
因此,while 循环采用以下形式。
while [ condition ]
do
commands 1
commands n
done
For 循环
#!/bin/bash
for (( counter=1; counter<=10; counter++ ))
do
echo -n "$counter "
done
printf "\n"
接收用户输入
#!/bin/bash
echo -n "Enter Something:"
read something
echo "You Entered: $something"
IF 语句
if CONDITION
then
STATEMENTS
fi
#!/bin/bash
echo -n "Enter a number:"
read num
if [[$num -gt 10]]
then
echo "Number is greater than 10."
fi
#!/bin/bash
echo -n "Enter a number: "
read num
if [[ $num -gt 10 ]]
then
echo "Number is greater than 10."
elif [[ $num -eq 10 ]]
then
echo "Number is equal to 10."
else
echo "Number is less than 10."
fi
#!/bin/bash
echo -n "Enter Number:"
read n
if [ $n -lt 10 ];
then
echo "It is a one digit number"
else
echo "It is a two digit number"
fi
使用 AND 运算符
#!/bin/bash
echo -n "Enter Number:"
read num
if [[ ( $num -lt 10 ) && ( $num%2 -eq 0 ) ]]; then
echo "Even Number"
else
echo "Odd Number"
fi
使用 OR 运算符
#!/bin/bash
echo -n "Enter any number:"
read n
if [[ ( $n -eq 15 || $n -eq 45 ) ]]
then
echo "You won"
else
echo "You lost!"
fi
case 条件
#!/bin/bash
echo -n "Enter a number: "
read num
case $num in
100)
echo "Hundred!!" ;;
200)
echo "Double Hundred!!" ;;
*)
echo "Neither 100 nor 200" ;;
esac
命令行参数
#!/bin/bash
echo "Total arguments : $#"
echo "First Argument = $1"
echo "Second Argument = $2"
# test.sh
./test.sh Hey Howdy
使用名称获取参数
#!/bin/bash
for arg in "$@"
do
index=$(echo $arg | cut -f1 -d=)
val=$(echo $arg | cut -f2 -d=)
case $index in
X) x=$val;;
Y) y=$val;;
*)
esac
done
((result=x+y))
echo "X+Y=$result"
调用
./test.sh X=44 Y=100
连接字符串
#!/bin/bash
string1="Ubuntu"
string2="Pit"
string=$string1$string2
echo "$string is a great resource for Linux beginners."
字符串截取
#!/bin/bash
Str="Learn Bash Commands from UbuntuPit"
subStr=${Str:0:20}
echo $subStr
使用 cut 做截取
#!/bin/bash
Str="Learn Bash Commands from UbuntuPit"
#subStr=${Str:0:20}
subStr=$(echo $Str| cut -d ' ' -f 1-3)
echo $subStr
添加两个值
#!/bin/bash
echo -n "Enter first number:"
read x
echo -n "Enter second number:"
read y
(( sum=x+y ))
echo "The result of addition=$sum"
添加多个值
#!/bin/bash
sum=0
for (( counter=1; counter<5; counter++ ))
do
echo -n "Enter Your Number:"
read n
(( sum+=n ))
#echo -n "$counter "
done
printf "\n"
echo "Result is: $sum"
Bash 中的函数
#!/bin/bash
function Add()
{
echo -n "Enter a Number: "
read x
echo -n "Enter another Number: "
read y
echo "Adiition is: $(( x+y ))"
}
Add
具有返回值的函数
#!/bin/bash
function Greet() {
str="Hello $name, what brings you to UbuntuPit.com?"
echo $str
}
echo "-> what's your name?"
read name
val=$(Greet)
echo -e "-> $val"
从 Bash 脚本创建目录
#!/bin/bash
echo -n "Enter directory name ->"
read newdir
cmd="mkdir $newdir"
eval $cmd
确认存在后创建目录
#!/bin/bash
echo -n "Enter directory name ->"
read dir
if [ -d "$dir" ]
then
echo "Directory exists"
else
`mkdir $dir`
# 或者 cmd="mkdir $dir" ; eval $cmd
echo "Directory created"
fi
读取文件
#!/bin/bash
file='editors.txt'
while read line; do
echo $line
done < $file
删除文件
#!/bin/bash
echo -n "Enter filename ->"
read name
rm -i $name
附加到文件
#!/bin/bash
echo "Before appending the file"
cat editors.txt
echo "6. NotePad++" >> editors.txt
echo "After appending the file"
cat editors.txt
测试文件存在
-f 文件
-d 文件夹
#!/bin/bash
filename=$1
if [ -f "$filename" ]; then
echo "File exists"
else
echo "File does not exist"
fi
从 Shell 脚本发送邮件
向收件人发送包含给定主题和消息的电子邮件
#!/bin/bash
recipient=”admin@example.com”
subject=”Greetings”
message=”Welcome to UbuntuPit”
`mail -s $subject $recipient <<< $message`
解析日期和时间
#!/bin/bash
year=`date +%Y`
month=`date +%m`
day=`date +%d`
hour=`date +%H`
minute=`date +%M`
second=`date +%S`
echo `date`
echo "Current Date is: $day-$month-$year"
echo "Current Time is: $hour:$minute:$second"
# Thu Apr 13 13:52:08 CST 2019
# Current Date is: 13-04-2019
# Current Time is: 13:52:08
sleep 命令
#!/bin/bash
echo "How long to wait?"
read time
sleep $time
echo "Waited for $time seconds!"
wait 命令
wait 命令用于暂停 Linux bash 脚本中的系统进程
#!/bin/bash
echo "Testing wait command"
sleep 5 &
pid=$!
kill $pid
wait $pid
echo $pid was terminated.
显示上次更新的文件
列出当前工作目录中最近更新或创建的文件
ls -lrt | grep ^- | awk 'END{print $NF}'
添加批处理扩展
对目录中的所有文件应用自定义扩展名
#!/bin/bash
dir=$1
for file in `ls $1/*`
do
mv $file $file.pdf
done
打印文件或目录的数量
查找给定目录中存在的文件或文件夹的数量 如果指定的目录不可用或存在权限问题,程序将要求用户重试。
#!/bin/bash
if [ -d "$@" ]; then
echo "Files found: $(find "$@" -type f | wc -l)"
echo "Folders found: $(find "$@" -type d | wc -l)"
else
echo "[ERROR] Please retry with another folder."
exit 1
fi
清理日志文件
#!/bin/bash
LOG_DIR=/var/log
cd $LOG_DIR
cat /dev/null > messages
cat /dev/null > wtmp
echo "Logs cleaned up."
使用 Bash 备份脚本
备份过去 24 小时内修改的每个文件或目录
#!/bin/bash
BACKUPFILE=backup-$(date +%m-%d-%Y)
archive=${1:-$BACKUPFILE}
find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar"
echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."
exit 0
检查你是否是 root 用户
#!/bin/bash
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]
then
echo "You are root."
else
echo "You are not root"
fi
exit 0
从文件中删除重复行
逐行遍历文件并删除所有重复的行。然后,它将新内容放入新文件,并保持原始文件的完整性。
#! /bin/sh
echo -n "Enter Filename-> "
read filename
if [ -f "$filename" ]; then
sort $filename | uniq | tee sorted.txt
else
echo "No $filename in $pwd...try again"
fi
exit 0
系统维护
#!/bin/bash
echo -e "\n$(date "+%d-%m-%Y --- %T") --- Starting work\n"
apt-get update
apt-get -y upgrade
apt-get -y autoremove
apt-get autoclean
echo -e "\n$(date "+%T") \t Script Terminated"
Last updated