使用shell脚本辅助系统维护RHCE-Day12

来源:互联网 发布:淘宝睡衣货到付款 编辑:程序博客网 时间:2024/06/05 16:51
shell脚本有多种类型,像bash、csh等。使用
#echo $0 查看类型


步骤:
1、新建脚本文件   *.sh 
2、编写脚本 
3、添加执行权限 




输入/输出设备
标准输入设备 /dev/stdin 0
标准输出设备 /dev/stdout
标准错误输出设备 /dev/stderr

重定向
传统的Unix系的系统是将命令默认从标准输入设备输入,在从标准输出结果输出显示。标准输入设备指键盘,标准输出设备则是终端显示器。Linux中,可以指定命令输入输出,不再局限于标准的输入或是输出设备,比如用文件作为输入,用文件作为输出,所以也叫重定向。


输出重定向
>:仅能重定向正确输出 追加>>
2>:仅能重定向错误输出
&>:同时重定向标准输出、标准错误输出
/dev/null 
# id tom &> /dev/null 
重定向到/dev/null,将不会在终端输出,要在终端输出使用/dev/stdout

输入重定向
<


# tr 'a-z' 'A-Z' < /tmp/1.txt 
tr命令将前面的字符串替换成后面的






输出语句 


1、echo 


# echo "hello world"
hello world


# echo -n "hello world" 不打印空行
hello world
不换行输出


# echo -e "hello world\nhello linux"
hello world
hello linux
-e解释引号中出现的符号


\n:换行
\t:tab空白


单引号'':所有字符会失去特殊含义
双绰号"":特殊字符会被转义 




2、printf 


# printf "hello world"
hello world




3、HERE DOCUMENT 


# cat << EOF
> a
> bb
> ccc
> EOF
a
bb
ccc




交互式命令的处理
不需要在提示会话的功能


# echo "redhat" | passwd --stdin tom
修改用户名tom的密码为redhat


# echo "hello linux" | mail -s "aaa" root


# echo -e "n\np\n2\n\n+100M\nw\n" | fdisk /dev/sdb &> /dev/null








变量 
用户自定义变量
环境变量
特殊变量 




用户自定义变量


1、定义变量 


变量名称=变量值 
# a=10 




2、调用变量值


$变量名称 

# animal=dog
# echo "It is a $animal"
It is a dog



${变量名称}
# animal=dog
# echo "there are some ${animal}s"
there are some dogs


shell中所有变量的值默认是作为字符处理




3、使用变量的值进行数学运算


方法1:$((expression))
双括号


# a=10
# b=20


# c=$((a+b))
# echo $c
30




方法2:let关键字


# a=10
# b=20


# let c=a+b 
# echo $c
30




方法3:declare关键字


# a=10
# b=20


# declare -i c=a+b  
其中-i表示当成integer
# echo $c
30


运算符:+, -, *, /, %
/:整除,小数部分无条件去掉
%:取余


生成10以内的随机数
# echo $((RANDOM%10))






4、将命令的执行结果赋予变量
反引号 ``中的内容被解释成命令去执行
# a=`ls -ldh /etc/`
# echo $a
drwxr-xr-x. 116 root root 12K May 28 10:39 /etc/

$(commond)
# b=$(date +%F-%T)
# echo $b
2016-05-28-11:12:21




5、删除变量 


# unset <变量名称> 






环境变量

1、查看环境变量
# env 


2、定义环境变量 


# export 变量名称=变量值 (-n删除,-p列出所有)
但是export加入的环境变量在重新开机之失去效果
/etc/profile 所有用户使用的环境变量
/etc/bashrc 当前用户使用的环境变量




export -n 变量名 删除环境变量
# export -n JAVA

export只有在bash shell下才能被执行。它只有被bash的解释器解释。
特殊变量
$?:判断命令的执行状态 
0:执行成功
1--255:执行失败



编写脚本,创建用户userA,并为用户设置初始密码为123456


#!/bin/bash


#!/bin/bash是特殊标记,不是注释。


useradd userA
echo "123456" | passwd --stdin userA &> /dev/null
echo "userA create finished,the password is 123456"




#!/bin/bash


name=userD


useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
echo "$name create finished,the password is 123456"




#!/bin/bash


read -p "please input username: " name


useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
echo "$name create finished,the password is 123456"



编写脚本,配置本地yum源


#!/bin/bash
#


mount /dev/cdrom /mnt &> /dev/null


rm -rf /etc/yum.repos.d/*


cat << EOF > /etc/yum.repos.d/yum.repo
[local]
name=localyum
baseurl=file:///mnt
enabled=1
gpgcheck=0
EOF


yum repolist all




分支结构


if
case 

if语句 


结构1:


if condition; then 
statement1
statement2
...
fi 


condition条件:
中括号一定要有空格
[ condition ]
command


数字表达式
字符表达式
文件/目录表达式


数字表达式
[ number1 -eq number2 ]-eq  = 
[ number1 -ne number2 ]-ne  !=
[ number1 -gt number2 ]-gt  >
[ number1 -ge number2 ]-ge  >=
[ number1 -lt number2 ]-lt  <
[ number1 -le number2 ]-le  <=




编写脚本,由用户输入用户名,如果用户不存在,则创建该用户,并设置密码为123456


#!/bin/bash
#


read -p "Input username: " name


id $name &> /dev/null
result=$?


if [ $result -ne 0 ]; then
useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
echo "$name create finished,the password is 123456"
fi


#!/bin/bash
#


read -p "Input username: " name


if ! id $name &> /dev/null; then
useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
echo "$name create finished,the password is 123456"
fi


结构2:


if condition; then 
statement1
statement2
...
else
statement1
statement2
...
fi 


编写脚本,由用户输入用户名,如果用户不存在,则创建该用户,并设置密码为123456;
否则,提示用户已经存在


#!/bin/bash
#


read -p "Input username: " name


if ! id $name &> /dev/null; then
useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
echo "$name create finished,the password is 123456"
else
echo "$name already exist"
fi




编写脚本,由用户输入用户名,判断该用户的uid及gid,如果相同,则显示Good user; 
否则显示Bad user.


#!/bin/bash
#


read -p "Input username: " name


user_id=`id -u $name`
group_id=`id -g $name`


if [ $user_id -eq $group_id ];then
echo "Good user."
else
echo "Bad user."
fi






awk:

默认以空白字符分割文本,按域分割


# awk '{print $2}' /1.txt 
is
is


# awk '{print $1,$4}' /1.txt
this test.
it awk


选项:
-F 指定行分割符 

# head -3 /etc/passwd | tail -1 | awk -F: '{print $1,$7}'
daemon /sbin/nologin




编写脚本,判断光盘是否挂载,挂载则显示挂载点;反之,将光盘挂载到/mnt 


#!/bin/bash
#


if df -h | grep sr0 &> /dev/null; then
mount_point=`df -h | grep sr0 | awk '{print $6}'`
echo "CDROM has been mounted $mount_point"
else
mount /dev/cdrom /mnt &> /dev/null
echo "CDROM has been mounted"
fi




结构3:


if condition; then 
statement1
statement2
...
elif condition; then 
statement1
statement2
...
elif condition; then 
statement1
statement2
...
else 
statement1
statement2
...
fi 


同时判断多个条件


AND:[ condition1 -a condition2 ],  [ condition1 ] && [ condition2 ]
OR: [ condition1 -o condition2 ],  [ condition1 ] || [ condition2 ]


编写脚本,取出系统时间的小时,对数字进行判断 
   6--10  this is morning 
   11-13  this is noon 
   14-18  this is afternoon 
   其他   this is night 


#!/bin/bash
#


hour=`date +%H`


if [ $hour -ge 6 -a $hour -le 10 ];then
echo "This is morning"
elif [ $hour -ge 11 -a $hour -le 13 ];then
echo "This is noon"
elif [ $hour -ge 14 -a $hour -le 18 ];then
echo "This is afternoon"
else
echo "This is night"
fi






结构4:


if condition; then 
if condition; then 
statement1
statement2
...
else
statement1
statement2
...
fi 
else 
statement1
statement2
...
fi 


字符表达式:
[ str1 == str2 ][ num1 -eq num2 ] 双目表达式
[ str1 != str2 ]
[ -z str1 ] 判断字符串是否为空

文件/目录表达式
[ -e file ] 判断文件是否存在
[ -f file ] 判断是否为文件
[ -d file ] 判断是否为目录
[ -r file ] 判断是否拥有read权限
[ -w file ] 判断是否拥有write权限
[ ! -x file ] 判断是否拥有exec权限 单目表达式




编写脚本,由用户输入一个文件名,判断该文件是否存在,
如果存在,再判断文件中是否存在空白行,则显示该文件中空白行的行数,没有空行,
则显示文件内容,并在每行前加入行号;如果不存在,则显示文件不存在


#!/bin/bash
#


read -p "Input filename: " file


if [ -f $file ];then 


# grep "^$" $file输出文件中的空行
if grep "^$" $file &> /dev/null; then
line=`grep ^$ $file | wc -l`
echo "The null line of $file : $line"
else
cat -n $file
fi
else
echo "$file not exist"
fi






编写脚本,由用户输入用户名,判断用户是否存在,
如果不存在,创建用户,设置初始密码为123456,要求用户首次登录时必须修改密码
,如果存在,以下面格式输出用户相关信息:
UserName:
HomeDir:
Shell:


#!/bin/bash
#


read -p "Input username : " name


if id $name &> /dev/null;then
home_dir=`grep "^$name:" /etc/passwd | awk -F: '{print $6}'`
user_shell=`grep "^$name:" /etc/passwd | awk -F: '{print $7}'`
echo "Username: $name"
echo "HomeDir: $home_dir"
echo "Shell: $user_shell"
else
useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
# passed -e
passwd -e $name &> /dev/null
echo "$name create finished, the default password is 123456"
fi






分支语句----case 


结构:


case variable in 
value1)
statement1
statement2
...
;;
value2)
statement1
statement2
...
;;
*)
statement1
statement2
...
;;
esac




编写脚本,由用户输入字符串,字符串为linux则显示windows,为windows则显示Linux
否则显示Other 


#!/bin/bash
#


read -p "Input string: " str


case $str in
    windows)
        echo "Linux..."
        ;;
    linux)
        echo "Windows..."
        ;;
    *)
        echo "Other...."
        ;;
esac




特殊变量:
$?:命令执行状态 
0--255 
0:成功

位置变量:
$1, $2, $3, $4......$9, ${10} 
$0:命令本身
$#:参数的个数






判断用户输入的字符,小写字符显示lower,大写字符显示upper
数字显示digit,其他则显示speical char


#!/bin/bash
#


read -p "Input char: " char


case $char in
    [[:lower:]]*)
       echo "lower..."
       ;;
    [[:upper:]]*)
        echo "Upper..."
        ;;
    [[:digit:]]*)
        echo "digit..."
        ;;
    *)
        echo "Special char..."
        ;;
esac






编写脚本,运行脚本时后面必须跟一个参数,如果参数为linux则显示window,如果是
windows则显示linux,否则显示other


#!/bin/bash
#


case $1 in
linux|Linux)
echo "Windows..."
;;
windows|Windows)
echo "linux..."
;;
*)
echo "Other..."
;;
esac






#!/bin/bash
#


if [ -z $1 ];then
echo "Usage ./os.sh { linux | windows }"
exit 8
# exit 8是加上一个判断,输入到一个日志文件中,便于排错,用echo $?可以查到
fi


case $1 in
linux|Linux)
echo "Windows..."
;;
windows|Windows)
echo "linux..."
;;
*)
echo "Other..."
;;
esac




#!/bin/bash
#


if [ $# -ne 1 ];then
echo "Usage ./os.sh { linux | windows }"
exit 8
fi


case $1 in
linux|Linux)
echo "Windows..."
;;
windows|Windows)
echo "linux..."
;;
*)
echo "Other..."
;;
esac




#!/bin/bash
#


if [ $# -ne 1 ];then
echo "Usage: `basename $0` { linux | windows }"
exit 8
fi


case $1 in
linux|Linux)
echo "Windows..."
;;
windows|Windows)
echo "linux..."
;;
*)
echo "Other..."
;;
esac






函数 


1、定义函数


方法1: 


function 函数名称{
statement1
statement2
...
}




方法2: 


函数名称() {
statement1
statement2
...





2、调用函数


函数名称 




使用位置变量给函数传递参数:


#!/bin/bash


sayHi() {
echo $1
}


sayHi abc 




编写脚本,提供给用户功能菜单,包括创建目录及删除目录,
根据用户的需求分别实现创建、删除目录功能,创建、删除目录的功能使用函数实现
This tool provide these function:
create directory(c|C)
delete direcotry(d|D)
quit(q|Q)




#!/bin/bash
#


cat << eof
This tool provide these function:
create directory(c|C)
delete direcotry(d|D)
quit(q|Q)
eof


create_dir() {
if [ ! -d $1 ];then
mkdir -p $1
echo "$1 create finished."
else
echo "$1 already exist"
fi
}
delete_dir() {
read -p "Input dir: " dir
if [ -d $dir ];then
rm -rf $dir
echo "$dir has been deleted..."
else
echo "$dir not exist,try again"
fi


}
read -p "Input choice: " choice
case $choice in
c|C)
read -p "Input dir: " dir
create_dir $dir
;;
d|D)
delete_dir
;;
q|Q)
exit 0
;;
esac




编写脚本 
列出如下功能菜单:
provide these tools:
 Add user(A|a)
 Del user(D|d)
 Modify user(M|m)
 quit(Q|q)


A|a   创建用户,并为用户设置初始密码为123456
D|d  删除用户,提示输入用户名
M|m  修改用户的shell,提示输入用户名;
用户的旧shell名称显示出来,再提示输入新的shell程序,
q|Q  退出脚本  Thank you…….




#!/bin/bash
#




create_user() {
if ! id $1 &> /dev/null;then
useradd $1
echo "123456" | passwd --stdin $1 &> /dev/null
passwd -e $1 &> /dev/null
# passed -d 下次用户登录时必须修改密码的提示
echo "$1 create finished,the default password is 123456"
else
echo "$1 already exist."
fi
}


delete_user() {
if id $1 &> /dev/null; then 
userdel -r $1
echo "$1 has been removed"
fi
}


modify_user() {
if id $1 &> /dev/null;then
old_shell=`grep "^$1:" /etc/passwd | awk -F: '{print $7}'`
echo "$1 old shell is $old_shell"
echo "Support shell:"
cat -n /etc/shells
read -p "Input new shell: " new_shell
usermod -s $new_shell $1
echo "$1 shell has been modified to $new_shell"
else
echo "$1 not exist..."
fi


}


cat << EOF
provide these tools:
 Add user(A|a)
 Del user(D|d)
 Modify user(M|m)
 quit(Q|q)
EOF


read -p "Input choice: " choice
case $choice in
a|A)
read -p "Input username: " name
create_user $name
;;
d|D)
read -p "Input username: " name
delete_user $name
;;
m|M)
read -p "Input username: " name
modify_user $name
;;
q|Q)
exit 0
;;
esac






安装nginx,编写nginx服务脚本(老系统,rhel7之前)


# tar zxf nginx-1.4.7.tar.gz 
# cd nginx-1.4.7
# ./configure --prefix=/usr/local/nginx --pid-path=/var/run/nginx.pid


# yum install -y pcre-devel 
# make && make install 




编写脚本: 


# vim /etc/init.d/nginx 


#!/bin/bash
# chkconfig: 2345 85 15
# Description: nginx service script 


nginx_cmd=/usr/local/nginx/sbin/nginx
pid_file=/var/run/nginx.pid




start() {
$nginx_cmd
if [ $? -eq 0 ];then
echo "service nginx start.....................[ok]"
touch /var/lock/subsys/nginx
fi
}


stop() {
$nginx_cmd -s stop 
if [ $? -eq 0 ];then
echo " service nginx stop.......................[ok]"
fi
}
status() {
if [ -f $pid_file ];then
echo "nginx( pid `cat $pid_file` ) is running"
else
echo "nginx is stopped"
fi
}


# main script
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
reload)
kill -1 `cat /var/run/nginx.pid`
;;
configtest)
$nginx_cmd -t
;;
status)
status
;;
*)
echo "Usage: `basename $0` { start | stop | restart | reload | configtest}"
;;
esac


# chkconfig --add nginx //添加为系统服务


# service nginx {start | stop | restart | reload | configtest }
# chkconfig nginx { on | off }










循环结构 


循环开始的条件
循环操作代码
循环结束的条件


循环语句:
for, while, util




for循环结构:


for variable in sequence; do 
statement1
statement2
....
done




sequence取值序列:
数字 
1 2 3
{1..100}
seq 10 
seq 2 5 
seq 1 2 10 生成1--10所有奇数


字符:
a b c 
"hello world" "hello linxu"
文件:
cat /etc/hosts




编写脚本,计算1--100的和


#!/bin/bash
#


sum=0


for i in {1..100};do
   let sum=$sum+$i
done


echo $sum




编写脚本,计算1--100的所有偶数的和


#!/bin/bash
#


sum=0


for i in {1..100};do
  let ys=$i%2
  if [ $ys -eq 0 ];then
    let sum=$sum+$i
  fi
done


echo $sum






编写脚本,创建用户user1----user100, 设置初始密码为123456; 提示 


#!/bin/bash
#


for i in `seq 100`;do
   useradd  user$i
   echo "123456" | passwd --stdin user$i &> /dev/null
   echo "user$i create finished, the default password is 123456"
done




编写脚本,判断10.1.1.0/24在线主机(考题)




#!/bin/bash
#


network=10.1.1.


for i in {1..254};do
  if ping -c 1 -w 1 $network$i &> /dev/null;then
#-c: 表示次数 -w: 表示deadline, 也就是ping的时间,所以ping -c 1 -w 1就是ping一次,超时1s
    echo "Host $network$i is up"
  else
    echo "Host $network$i is down"
  fi
done




172.16.0.0/16 


172.16.0.1 -------------- 172.16.0.255 
172.16.1.1 -------------- 172.16.1.255 
172.16.2.1 -------------- 172.16.2.255 
172.16.3.1 -------------- 172.16.3.255 
.....
.....
172.16.255.1  ----------- 172.16.255.254 


#!/bin/bash 


network=172.16.


for i in {0..255};do
   for j in {1..255};do
      if ping -c 1 -w 1 $network$i.$j &> /dev/null;then
        echo "$network$i.$j is up"
      else
        echo "$network$i.$j is down"
      fi
    done
done




编写脚本,批量创建用户harry,alex,alix,natasha,fish


#!/bin/bash
#


for i in natsha alex alix harry fish;do
   useradd $i
done




编写脚本,向系统中所有用户打招呼 


#!/bin/bash
#


for i in `awk -F: '{print $1}' /etc/passwd`;do
   echo "Hello, $i"
done




编写脚本, 分别统计/sbin/nologin的用户个数及/bin/bash用户的个数


#!/bin/bash
#


bnumber=0
snumber=0


line=`wc -l /etc/passwd | awk '{print $1}'`


for i in `seq $line`;do
   sh=`head -$i /etc/passwd | tail -1 | awk -F: '{print $7}'`
   case $sh in 
    "/bin/bash")
bnumber=$((bnumber+1))
;;
    "/sbin/nologin")
snumber=$((snumber+1))
;;
   esac
done
echo "The number of user whose shell is /bin/bash: $bnumber"
echo "The number of user whose shell is /sbin/noglogin: $snumber"




跳板机:

编写脚本,实现在10.1.1.1和10.1.1.2上安装tomcat软件 


配置基于密钥的ssh:


1、生成密钥对
# ssh-keygen -t rsa 


2、复制公钥到服务器
# ssh-copy-id -i /root/.ssh/id_rsa.pub 10.1.1.1 
# ssh-copy-id -i /root/.ssh/id_rsa.pub 10.1.1.2 




#!/bin/bash
#


network=10.1.1.


for i in 1 2;do
   ssh $network$i 'yum install -y tomcat*'
done








break,continue语句 

break:中断整个循环
continue:中断本次循环,继续下一次循环


编写脚本,计算1到100的和,输出和为3000时的被加数


#!/bin/bash
#


sum=0


for i in {1..100};do
   let sum=$sum+$i
   if [ $sum -ge 3000 ];then
break
   fi
done


echo $i




编写脚本,取出系统中shell为/bin/bash的前5个用户


#!/bin/bash
#


count=0


line=`wc -l /etc/passwd | awk '{print $1}'`


for i in `seq $line`;do
   sh=`head -$i /etc/passwd | tail -1 | awk -F: '{print $7}'`
   if [ $sh == /bin/bash ];then
      name=`head -$i /etc/passwd | tail -1 | awk -F: '{print $1}'`
  echo $name
      let count=$count+1
   fi
   if [ $count -eq 5 ];then
break
   fi
done










while循环语句 


while condition; do 
statement1
statement2
change_condition_statement
done 






编写脚本,利用while循环计算1--100的和


#!/bin/bash
#


sum=0
i=1


while [ $i -le 100 ];do
  let sum=$sum+$i
  let i++
done


echo $sum






编写脚本,由用户输入数字,数字为8时中止循环,否则不停地输入


#!/bin/bash
#


read -p "Input number: " number


while [ $number -ne 8 ];do
   read -p "Input number: " number
done


echo "You win..."






编写脚本,检测脚本文件语法 


#!/bin/bash
#


bash -n $1 &> /dev/null
result=$?


while [ $result -ne 0 ];do
   vim + $1
   bash -n $1 &> /dev/null
   result=$?
done




编写脚本,功能菜单 
provide these tools:
 show disk info(d)
 show mem info(m)
 show cpu info(c)
 quit(q)
 
 


#!/bin/bash
#


show_menu() {
cat << EOF
provide these tools:
 show disk info(d)
 show mem info(m)
 show cpu info(c)
 quit(q)
EOF
}


show_menu


read -p "Input choice: " choice
while [ $choice != q ];do
case $choice in
d)
echo "===========disk info=============="
df -hT
;;
m)
echo "==========meme info==============="
free -m
;;
c)
echo "==========cpu info================="
uptime
;;
q)
break
;;
*)
show_menu
;;
esac
read -p "Input choice: " choice
done




特殊用法:


while true;do
statement1
statement2
...
done 




编写脚本,每5秒钟显示一次CPU负载


#!/bin/bash
#


while true;do
  uptime
  sleep 5
done








#!/bin/bash
#




while true;do
  read -p "Input number: " number
  if [ $number -eq 8 ];then
echo "You win"
break
  fi
done






特殊用法 :


while read line; do 
statement1
statement2
....
done < filename 




#!/bin/bash
#


while read line;do
name=`echo $line | awk -F: '{print $1}'`
    echo "Hello $name"
done < /etc/passwd












循环结构--util 


util condition;do 
statement1
statement2
change_condition_statement
done 


注意: 条件为假执行循环,条件为真,停止循环

















shell脚本中对字符串的处理


1、${#变量名}
作用:返回字符串的长度
# foo="this is a test"
# echo ${#foo}           //返回字符串foo的长度          
14


2、${变量名:offset:length}
作用:截取字符串,length指定截取的长度,也可以不写;
字符串的第一个字符的索引值为0
# foo="abcdefg"
# echo ${foo:3:2}     //从下标为3的字符开始截取,共截取2个     
de
# echo ${foo:3}       //从下标为3的字符开始截取到最后的字符     
defg


3、${变量名#pattern}    ${变量名##parttern}
pattern:模式,通配符表达式
作用:清除字符串中符合pattern的字符
# foo="file.txt.zip"
# echo ${foo#*.}          //一个#号代表按照最短匹配清除
txt.zip
# echo ${foo##*.}         //2个#号代表按照最长匹配清除
zip


4、${变量名%pattern}    ${变量名%%parttern}
pattern:模式,通配符表达式
作用:清除字符串中符合pattern的字符,从字符串最后匹配
# echo $foo
file.txt.zip
# echo ${foo%.*}              //1个%代表按照最短匹配
file.txt
# echo ${foo%%.*}           //2个%%代表按照最长匹配
file


5、字符串替换操作
${变量名称/old/new}
# foo="txt.txt"
# echo ${foo/txt/TXT}        替换第1次出现的txt     
TXT.txt
# echo ${foo//txt/TXT}       替换字符串中所有的txt   
TXT.TXT
# echo ${foo/#txt/TXT}       只替换字符串中开头的txt  
TXT.txt
# echo ${foo/%txt/TXT}       只替换字符串中结尾的txt  
txt.TXT


6、实现大小写字母的转换
# foo="ABde"
# echo ${foo,,}      //将字符串foo全部转换成小写        
abde
# echo ${foo,}       //将字符串foo的第1个字符转换成小写
aBde
# echo ${foo^}      //将字符串foo的第1个字符转换成大写 
ABde
# echo ${foo^^}     //将字符串foo全部转换为大写         
ABDE








array: 数组


一段连续的内存空间
数组的下标从0开始


1、声明一个数组
# declare -a array_name


2、数组元素赋值方法
方法1:
array[0]=tom
array[1]=jerry
array[2]=mike
array[6]=natasha


方法2:
array=(tom jerry mike)
array=([0]=tom [1]=jerry [6]=mike)
数组下标可以不连续,但在下标6之前的元素会被初始化为空值
如果某个元素值中有空格,需要使用双引号


显示数组中所有元素
 ${array_name[*]}
 ${array_name[@]}
 
3、引用数组元素的值
${array[n]}
n: 数组下标 


# array=([0]=tom [1]=jerry [6]=mike)
# echo ${array[1]}
jerry


4、显示数组中下标为n的元素的字符长度
${#array[n]}


# array=([0]=tom [1]=jerry [6]=mike)
# echo ${#array[6]}
4


5、显示数组中值不为空的元素的个数
${#array[*]}  或者  ${#array[@]}


# array=([0]=tom [1]=jerry [6]=mike)
# echo ${#array[*]}
3






编写脚本,找出数组中最大值
#!/bin/bash
#


read -p "Input Array Length: " num


for i in `seq 0 $(($num-1))`;do
let number[$i]=$RANDOM%1000
done


echo "Array Values: ${number[*]}"


max=${number[0]}


let line=${#number[*]}-1


for i in `seq $line`;do
   if [ ${number[$i]} -gt $max ];then
max=${number[$i]}
   fi
done


echo "Max value: $max"





























0 0
原创粉丝点击