系统运维-15-2-Bash编程基础

本文介绍了Bash脚本中until、for循环的使用,以及如何通过while循环实现用户登录监控和输出乘法表。此外,还展示了如何用if-else和case语句处理用户输入,展示系统信息。
摘要由CSDN通过智能技术生成

1.使用until方式,求一定范围内的整数和。

vim summary.sh编辑脚本。bash -n summary.sh检查脚本。bash summary.sh执行脚本。cat summary.sh查看脚本。

[root@lab1 ~]# vim summary.sh
[root@lab1 ~]# bash -n summary.sh
[root@lab1 ~]# bash summary.sh
Summary: 5050
[root@lab1 ~]# cat summary.sh 
#!/bin/bash
#
declare -i i=1
declare -i sum=0

until [ $i -gt 100 ]; do
  let sum+=$i
  let i++
done

echo "Summary: $sum"
 

2.使用until方式,输出乘数表。

vim mult.sh编辑脚本。 bash -n mult.sh检查脚本。bash mult.sh执行脚本。 cat mult.sh查看脚本。

[root@lab1 ~]# vim mult.sh
[root@lab1 ~]# bash -n mult.sh
[root@lab1 ~]# bash mult.sh
1X1=1    
1X2=2    2X2=4    
1X3=3    2X3=6    3X3=9    
1X4=4    2X4=8    3X4=12    4X4=16    
1X5=5    2X5=10    3X5=15    4X5=20    5X5=25    
1X6=6    2X6=12    3X6=18    4X6=24    5X6=30    6X6=36    
1X7=7    2X7=14    3X7=21    4X7=28    5X7=35    6X7=42    7X7=49    
1X8=8    2X8=16    3X8=24    4X8=32    5X8=40    6X8=48    7X8=56    8X8=64    
1X9=9    2X9=18    3X9=27    4X9=36    5X9=45    6X9=54    7X9=63    8X9=72    9X9=81    
[root@lab1 ~]# cat mult.sh
#!/bin/bash
#
declare -i j=1
declare -i i=1

until [ $j -gt 9 ]; do
  until [ $i -gt $j ]; do
    echo -n -e "${i}X${j}=$[$i*$j]\t"
    let i++
  done
  echo
  let i=1
  let j++
done
 

3.使用until方式,求一定范围内的偶数和。

vim even.sh编辑脚本。bash -n even.sh检查脚本。bash even.sh执行脚本。cat even.sh查看脚本。

[root@lab1 ~]# vim even.sh
[root@lab1 ~]# bash -n even.sh
[root@lab1 ~]# bash even.sh
Even sum: 2550
[root@lab1 ~]# cat even.sh
#!/bin/bash
#
declare -i i=0
declare -i sum=0

until [ $i -gt 100 ]; do
  let i++
  if [ $[$i%2] -eq 1 ]; then
    continue
  fi
  let sum+=$i
done

echo "Even sum: $sum"

 

4.使用while+break方法,记录用户登陆信息。

vim user.sh编辑脚本。bash -n user.sh检查脚本。bash  user.sh执行脚本。cat user.sh查看脚本。useradd docker添加用户。echo docker | passwd --stdin docker设置密码。ssh docker@172.20.0.131登陆。cat /tmp/user.log查看日志记录进行确认。

[root@lab1 ~]# vim user.sh
[root@lab1 ~]# bash -n user.sh
[root@lab1 ~]# bash  user.sh
Enter a user name: docker

[root@lab1 ~]# cat user.sh
#!/bin/bash
#
read -p "Enter a user name: " username

while true; do
  if who | grep "^$username" &> /dev/null; then
    break
  fi
  sleep 3
done

echo "$username logged on." >> /tmp/user.log
[root@lab1 ~]# useradd docker
[root@lab1 ~]# echo docker | passwd --stdin docker
Changing password for user docker.
passwd: all authentication tokens updated successfully.

[C:\~]$ ssh docker@172.20.0.131
Connecting to 172.20.0.131:22...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
[root@lab1 ~]# cat /tmp/user.log
docker logged on.
 

5.使用while或者until方式,也可以实现上面的要求。注意:while ! 和 until在使用上基本等效。

[root@lab1 ~]# cp user.sh user2.sh 
[root@lab1 ~]# vim user2.sh
[root@lab1 ~]# cat user2.sh
#!/bin/bash
#
read -p "Enter a user name: " username

while ! who | grep "^$username" &> /dev/null; do
  sleep 3
done

echo "$username logged on." >> /tmp/user.log
[root@lab1 ~]# cp user2.sh user3.sh
[root@lab1 ~]# vim user3.sh
[root@lab1 ~]# cat user3.sh
#!/bin/bash
#
read -p "Enter a user name: " username

until who | grep "^$username" &> /dev/null; do
  sleep 3
done

echo "$username logged on." >> /tmp/user.log
 

6.使用while方法,获取uid为偶数的用户账户信息。

vim evenid.sh编辑脚本。bash -n evenid.sh检查脚本。bash evenid.sh执行脚本。cat evenid.sh查看脚本。

[root@lab1 ~]# vim evenid.sh
[root@lab1 ~]# bash -n evenid.sh
[root@lab1 ~]# bash evenid.sh
username: root    uid: 0
username: daemon    uid: 2
username: lp    uid: 4
username: shutdown    uid: 6
username: mail    uid: 8
username: games    uid: 12
username: ftp    uid: 14
username: systemd-network    uid: 192
username: sshd    uid: 74
username: chrony    uid: 998
username: student    uid: 1000
username: apache    uid: 48
username: user2    uid: 1002
username: user4    uid: 1004
username: user6    uid: 1006
username: user8    uid: 1008
username: user10    uid: 1010
username: user5    uid: 1012
[root@lab1 ~]# cat evenid.sh
#!/bin/bash
#

while read line; do
  if [ $[`echo $line | cut -d: -f3` % 2] -eq 0 ]; then
    echo -e -n "username: `echo $line | cut -d: -f1`\t"
    echo "uid: `echo $line | cut -d: -f3 `"
  fi
done < /etc/passwd

 

7.使用for的算术运算方式,求一定范围的整数和。

vim sum2.sh编辑脚本。bash -n sum2.sh检查脚本。bash sum2.sh执行脚本。 cat sum2.sh查看脚本

[root@lab1 ~]# vim sum2.sh
[root@lab1 ~]# bash -n sum2.sh
[root@lab1 ~]# bash sum2.sh
Sum: 5050.
[root@lab1 ~]# cat sum2.sh
#!/bin/bash
#
declare -i sum=0

for ((i=1;i<=100;i++)); do
  let sum+=$i
done

echo "Sum: $sum."

 

8.使用for的算术运算方式,输出乘法运算表。

vim mult2.sh编辑脚本。bash -n mult2.sh检查脚本。bash mult2.sh执行脚本。 cat mult2.sh查看脚本。

[root@lab1 ~]# vim mult2.sh
[root@lab1 ~]# bash -n mult2.sh
[root@lab1 ~]# bash mult2.sh
1X1=1    
1X2=2    2X2=4    
1X3=3    2X3=6    3X3=9    
1X4=4    2X4=8    3X4=12    4X4=16    
1X5=5    2X5=10    3X5=15    4X5=20    5X5=25    
1X6=6    2X6=12    3X6=18    4X6=24    5X6=30    6X6=36    
1X7=7    2X7=14    3X7=21    4X7=28    5X7=35    6X7=42    7X7=49    
1X8=8    2X8=16    3X8=24    4X8=32    5X8=40    6X8=48    7X8=56    8X8=64    
1X9=9    2X9=18    3X9=27    4X9=36    5X9=45    6X9=54    7X9=63    8X9=72    9X9=81    
[root@lab1 ~]# cat mult2.sh
#!/bin/bash
#

for ((j=1;j<=9;j++)); do
  for ((i=1;i<=j;i++)); do
    echo -e -n "${i}X${j}=$[$i*$j]\t"
  done
  echo
done
 

9.使用if + else方式,对输入进行指定输出。

vim sysinfo.sh编辑脚本。bash -n sysinfo.sh检查脚本。bash sysinfo.sh执行脚本。cat sysinfo.sh查看脚本。

[root@lab1 ~]# vim sysinfo.sh
[root@lab1 ~]# bash -n sysinfo.sh
[root@lab1 ~]# bash sysinfo.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: cpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 142
Model name:            Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
Stepping:              10
CPU MHz:               1991.538
BogoMIPS:              3984.00
Virtualization:        VT-x
Hypervisor vendor:     VMware
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0,1
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat
[root@lab1 ~]# bash sysinfo.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: mem
cat: /proc/meinfo: No such file or directory
[root@lab1 ~]# vim sysinfo.sh
[root@lab1 ~]# bash -n sysinfo.sh
[root@lab1 ~]# bash sysinfo.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: cpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 142
Model name:            Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
Stepping:              10
CPU MHz:               1991.538
BogoMIPS:              3984.00
Virtualization:        VT-x
Hypervisor vendor:     VMware
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0,1
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat
[root@lab1 ~]# bash sysinfo.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: mem
MemTotal:        1867048 kB
MemFree:         1342572 kB
MemAvailable:    1503228 kB
Buffers:            2108 kB
Cached:           281088 kB
SwapCached:            0 kB
Active:           233512 kB
Inactive:         137388 kB
Active(anon):      88160 kB
Inactive(anon):     8472 kB
Active(file):     145352 kB
Inactive(file):   128916 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:       2097148 kB
SwapFree:        2097148 kB
Dirty:                 8 kB
Writeback:             0 kB
AnonPages:         87748 kB
Mapped:            29548 kB
Shmem:              8928 kB
Slab:              79560 kB
SReclaimable:      35000 kB
SUnreclaim:        44560 kB
KernelStack:        4112 kB
PageTables:         7532 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     3030672 kB
Committed_AS:     318540 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      182432 kB
VmallocChunk:   34359310332 kB
HardwareCorrupted:     0 kB
AnonHugePages:     10240 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       75648 kB
DirectMap2M:     2021376 kB
DirectMap1G:           0 kB
[root@lab1 ~]# bash sysinfo.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: disk

Disk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000a2c70

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2099199     1048576   83  Linux
/dev/sda2         2099200    41943039    19921920   8e  Linux LVM

Disk /dev/mapper/centos-root: 18.2 GB, 18249416704 bytes, 35643392 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/centos-swap: 2147 MB, 2147483648 bytes, 4194304 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
[root@lab1 ~]# bash sysinfo.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: quit
Quit

[root@lab1 ~]# cat sysinfo.sh
#!/bin/bash
#
cat << EOF
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
EOF

read -p "Enter a option: " option
while [ "$option" != "cpu" -a "$option" != "mem" -a "$option" != "cpu" -a "$option" != "disk" -a "$option" != "quit" ]; do
  read -p "Wrong option, Enter again: " option
done

if [ "$option" == "cpu" ]; then
  lscpu
elif [ "$option" == "mem" ]; then
  cat /proc/meminfo
elif [ "$option" == "disk" ]; then
  fdisk -l
else
  echo "Quit"
  exit 0
fi
 

10.使用case方式,对输入进行指定输出。

vim sysinfo2.sh编辑脚本。bash -n sysinfo2.sh检查脚本。bash sysinfo2.sh执行脚本。cat sysinfo2.sh查看脚本。

[root@lab1 ~]# cp sysinfo.sh sysinfo2.sh 
[root@lab1 ~]# vim sysinfo2.sh
[root@lab1 ~]# bash -n sysinfo2.sh
[root@lab1 ~]# bash sysinfo2.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: cpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 142
Model name:            Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
Stepping:              10
CPU MHz:               1991.538
BogoMIPS:              3984.00
Virtualization:        VT-x
Hypervisor vendor:     VMware
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0,1
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat
[root@lab1 ~]# bash sysinfo2.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: mem
MemTotal:        1867048 kB
MemFree:         1342168 kB
MemAvailable:    1503048 kB
Buffers:            2112 kB
Cached:           281292 kB
SwapCached:            0 kB
Active:           233528 kB
Inactive:         137580 kB
Active(anon):      88160 kB
Inactive(anon):     8472 kB
Active(file):     145368 kB
Inactive(file):   129108 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:       2097148 kB
SwapFree:        2097148 kB
Dirty:                28 kB
Writeback:             0 kB
AnonPages:         87748 kB
Mapped:            29552 kB
Shmem:              8928 kB
Slab:              79592 kB
SReclaimable:      35032 kB
SUnreclaim:        44560 kB
KernelStack:        4112 kB
PageTables:         7536 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     3030672 kB
Committed_AS:     318544 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      182432 kB
VmallocChunk:   34359310332 kB
HardwareCorrupted:     0 kB
AnonHugePages:     10240 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       75648 kB
DirectMap2M:     2021376 kB
DirectMap1G:           0 kB
[root@lab1 ~]# bash sysinfo2.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: disk

Disk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000a2c70

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2099199     1048576   83  Linux
/dev/sda2         2099200    41943039    19921920   8e  Linux LVM

Disk /dev/mapper/centos-root: 18.2 GB, 18249416704 bytes, 35643392 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/centos-swap: 2147 MB, 2147483648 bytes, 4194304 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

[root@lab1 ~]# bash sysinfo2.sh
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
Enter a option: quit
Quit...

[root@lab1 ~]# cat sysinfo2.sh
#!/bin/bash
#
cat << EOF
cpu) show cpu information
mem) show memory information
disk) show disk information
quit) quit
=================================
EOF

read -p "Enter a option: " option
while [ "$option" != "cpu" -a "$option" != "mem" -a "$option" != "cpu" -a "$option" != "disk" -a "$option" != "quit" ]; do
  read -p "Wrong option, Enter again: " option
done

case "$option" in
cpu)
  lscpu
  ;;
mem)
  cat /proc/meminfo
  ;;
disk)
  fdisk -l
  ;;
*)
  echo "Quit..."
  exit 0
esac 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值