5 Shell Scripts for Linux Newbies to Learn Shell Programming – Part II

To Learn something you need to do it, without the fear of being unsuccessful. I believe in practicality and hence will be accompanying you to the practical world of Scripting Language.

Learn Basic Shell Scripting

This article is an extension of our First article Understand Linux Shell and Basic Shell Scripting – Part I, where we gave you a taste of Scripting, continuing that we won’t disappoint you in this article.

Script 1: Drawing a Special Pattern

#!/bin/bash
MAX_NO=0
echo -n "Enter Number between (5 to 9) : "
read MAX_NO
if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ] ; then
   echo "WTF... I ask to enter number between 5 and 9, Try Again"
   exit 1
fi
clear
for (( i=1; i<=MAX_NO; i++ )) do     for (( s=MAX_NO; s>=i; s-- ))
    do
       echo -n " "
    done
    for (( j=1; j<=i;  j++ ))     do      echo -n " ."      done     echo "" done ###### Second stage ###################### for (( i=MAX_NO; i>=1; i-- ))
do
    for (( s=i; s<=MAX_NO; s++ ))
    do
       echo -n " "
    done
    for (( j=1; j<=i;  j++ ))
    do
     echo -n " ."
    done
    echo ""
done
echo -e "\n\n\t\t\t Whenever you need help, Tecmint.com is always there"

Most of the above ‘key words‘ would be known to you and most of them are self explanatory. e.g., MAX sets the maximum value of the variable, for is a loop and anything within the loop gets on executing again and again till the loop is valid for given value of input.

Sample Output
[[email protected] ~]# chmod 755 Special_Pattern.sh
[[email protected] ~]# ./Special_Pattern.sh
Enter Number between (5 to 9) : 6
       .
      . .
     . . .
    . . . .
   . . . . .
  . . . . . .
  . . . . . .
   . . . . .
    . . . .
     . . .
      . .
       .

                         Whenever you need help, Tecmint.com is always there

If you are a little aware of any programming language, learning the above script is not difficult, even if you are new to computation, programming and Linux it is not going to be much difficult.

Download Special_Pattern.sh

Script 2: Creating Colorful Script

Who says, Linux is colorless and boring, save the codes below to anything [dotsh, make it executable and Run it, don’t forget to tell me how it was, Think what you can achieve, implementing it somewhere.

#!/bin/bash
clear
echo -e "33[1m Hello World"
# bold effect
echo -e "33[5m Blink"
# blink effect
echo -e "33[0m Hello World"
# back to normal
echo -e "33[31m Hello World"
# Red color
echo -e "33[32m Hello World"
# Green color
echo -e "33[33m Hello World"
# See remaining on screen
echo -e "33[34m Hello World"
echo -e "33[35m Hello World"
echo -e "33[36m Hello World"
echo -e -n "33[0m"
# back to normal
echo -e "33[41m Hello World"
echo -e "33[42m Hello World"
echo -e "33[43m Hello World"
echo -e "33[44m Hello World"
echo -e "33[45m Hello World"
echo -e "33[46m Hello World"
echo -e "33[0m Hello World"

Note: Don‘t bother about the color code now, Those important to you will be at your tongue, gradually.

Warning: Your terminal might not have the facility of blinking.

Sample Output
[[email protected] ~]# chmod 755 Colorfull.sh
[[email protected] ~]# ./Colorfull.sh

Hello World
Blink
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Download Colorfull.sh

Script 3: Encrypt a File/Directory

This script will encrypt a file (remember? directory/driver/…. everything is treated as file, inLinux). The current limitation of the above script is that it don’t support auto completion of name using TAB. Moreover, you need to place the script and file to be encrypted in the same folder. You may need to install “pinentry-gui”, using yum or apt the package, if required.

[[email protected] ~]# yum install pinentry-gui
[[email protected] ~]# apt-get install pinentry-gui

Crete a file called “Encrypt.sh” and place the following script, make it executable and run it as shown.

#!/bin/bash
echo "Welcome, I am ready to encrypt a file/folder for you"
echo "currently I have a limitation, Place me to thh same folder, where a file to be
encrypted is present"
echo "Enter the Exact File Name with extension"
read file;
gpg -c $file
echo "I have encrypted the file successfully..."
echo "Now I will be removing the original file"
rm -rf $file

Sample Output

[[email protected] ~]# chmod 755 Encrypt.sh
[[email protected] ~]# ./Encrypt.sh

Welcome, I am ready to encrypt a file/folder for you
currently I have a limitation, Place me to the same folder, where a file to be

encrypted is present
Enter the Exact File Name with extension

package.xml

                                                   ┌─────────────────────────────────────────────────────┐
                                                   │ Enter passphrase                                    │
                                                   │                                                     │
                                                   │                                                     │
                                                   │ Passphrase *******_________________________________ │
                                                   │                                                     │
                                                   │       <OK>                             <Cancel>     │
                                                   └─────────────────────────────────────────────────────┘

Please re-enter this passphrase

                                                   ┌─────────────────────────────────────────────────────┐
                                                   │ Please re-enter this passphrase                     │
                                                   │                                                     │
                                                   │ Passphrase ********________________________________ │
                                                   │                                                     │
                                                   │       <OK>                             <Cancel>     │
                                                   └─────────────────────────────────────────────────────┘

I have encrypted the file successfully...
Now I will be removing the original file
</pre>

gpg -c : This will encrypt your file, using a passkey aka password. In this process of learning you would have never thought that the actual process of learning could be that much easy. So after encrypting a file what you need? Obviously! decrypting the file. And I want you – the learner, the reader to write the decryption script yourself, don’t worry I am not leaving you in the middle, I just want you to gain something out of this article.

Notegpg -d filename.gpg > filename is what you need to implement in your decryption script. You may post you script in comment if successful, if not you may ask me to write it for you.

Download Encrypt.sh

Script 4: Checking Server Utilization

Checking the server utilization is one of the important task of an administrator, and a good administrator is one who knows how to automate his day to day task. Below is the script that will give many such information about your server. Check it yourself.

#!/bin/bash
    date;
    echo "uptime:"
    uptime
    echo "Currently connected:"
    w
    echo "--------------------"
    echo "Last logins:"
    last -a |head -3
    echo "--------------------"
    echo "Disk and memory usage:"
    df -h | xargs | awk ‘{print "Free/total disk: " $11 " / " $9}‘
    free -m | xargs | awk ‘{print "Free/total memory: " $17 " / " $8 " MB"}‘
    echo "--------------------"
    start_log=`head -1 /var/log/messages |cut -c 1-12`
    oom=`grep -ci kill /var/log/messages`
    echo -n "OOM errors since $start_log :" $oom
    echo ""
    echo "--------------------"
    echo "Utilization and most expensive processes:"
    top -b |head -3
    echo
	top -b |head -10 |tail -4
    echo "--------------------"
    echo "Open TCP ports:"
    nmap -p- -T4 127.0.0.1
    echo "--------------------"
    echo "Current connections:"
    ss -s
    echo "--------------------"
    echo "processes:"
    ps auxf --width=200
    echo "--------------------"
    echo "vmstat:"
    vmstat 1 5
Sample Output
[[email protected] ~]# chmod 755 Server-Health.sh
[[email protected] ~]# ./Server-Health.sh

Tue Jul 16 22:01:06 IST 2013
uptime:
 22:01:06 up 174 days,  4:42,  1 user,  load average: 0.36, 0.25, 0.18
Currently connected:
 22:01:06 up 174 days,  4:42,  1 user,  load average: 0.36, 0.25, 0.18
USER     TTY      FROM              [email protected]   IDLE   JCPU   PCPU WHAT
tecmint   pts/0    116.72.134.162   21:48    0.00s  0.03s  0.03s sshd: tecmint [priv]
--------------------
Last logins:
tecmint   pts/0        Tue Jul 16 21:48   still logged in    116.72.134.162
tecmint   pts/0        Tue Jul 16 21:24 - 21:43  (00:19)     116.72.134.162
--------------------
Disk and memory usage:
Free/total disk: 292G / 457G
Free/total memory: 3510 / 3838 MB
--------------------
OOM errors since Jul 14 03:37 : 0
--------------------
Utilization and most expensive processes:
top - 22:01:07 up 174 days,  4:42,  1 user,  load average: 0.36, 0.25, 0.18
Tasks: 149 total,   1 running, 148 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.1%us,  0.0%sy,  0.0%ni, 99.3%id,  0.6%wa,  0.0%hi,  0.0%si,  0.0%st

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0  3788 1128  932 S  0.0  0.0   0:32.94 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      RT   0     0    0    0 S  0.0  0.0   0:14.07 migration/0

Note: I have given you the script that gives the output in the terminal itself, how about getting the output in a file for future reference. Implement it using redirect operator.

  1. >‘ : the redirection operator causes a file creation, and if it does exist, the contents are overwritten.
  2. >>‘ : when you use >>, you are adding information, rather than replacing it.
  3. >>‘ is safe, as compared to ‘>

Download Server-Health.sh

Script 5: Check Disk Space and Sends an Email Alert

How about getting an email when disk use in partition PART is bigger than Maximum allowed, it is a life saver script for web administrators with little modification.

MAX=95
[email protected]
PART=sda1
USE=`df -h |grep $PART | awk ‘{ print $5 }‘ | cut -d‘%‘ -f1`
if [ $USE -gt $MAX ]; then
  echo "Percent used: $USE" | mail -s "Running out of disk space" $EMAIL
fi

Note: Remove “USER” with your user name. You can check mail using using ‘mail‘ command.

Download Check-Disk-Space.sh

Script writing and programming is beyond boundaries, anything and everything could be implemented as required. That’s all for now, In my very next article I will be giving your some different flavors of scripting. Till then stay cool and tuned, enjoy.

(from:http://www.tecmint.com/basic-shell-programming-part-ii/)

5 Shell Scripts for Linux Newbies to Learn Shell Programming – Part II

时间: 2024-10-12 14:51:29

5 Shell Scripts for Linux Newbies to Learn Shell Programming – Part II的相关文章

《Linux命令行与shell脚本编程大全》学习笔记(转)

第一部分:Linux命令行<Linux命令行与shell脚本编程大全> 第一章:初识Linux shell<Linux命令行与shell脚本编程大全> 第二章:走进shell<Linux命令行与shell脚本编程大全> 第三章:基本的bash shell命令<Linux命令行与shell脚本编程大全> 第四章:更多的bash shell命令<Linux命令行与shell脚本编程大全> 第五章:使用Linux环境变量<Linux命令行与she

鸟哥的Linux私房菜_基础版_学习笔记9:第十三章 学习 Shell Scripts

13.1 什么是 Shell scripts 13.1.1 干嘛学习 shell scripts 13.1.2 第一支 script 的撰写与运行 在 shell script 的撰写中还需要用到底下的注意事项: 命令的运行是从上而下.从左而右的分析与运行: 命令的下达就如同第五章内提到的: 命令.选项与参数间的多个空白都会被忽略掉: 空白行也将被忽略掉,并且 [tab] 按键所推开的空白同样视为空白键: 如果读取到一个 Enter 符号 (CR) ,就尝试开始运行该行 (或该串) 命令: 至於

鸟哥的 Linux 私房菜Shell Scripts篇(一)

12.1 什么是 Shell scripts 什么是 shell script (程序化脚本) 呢?就字面上的意义,我们将他分为两部份. 在" shell"部分,我们在 十章的 BASH 当中已经提过了,那是一个命令行下面让我们与系统沟通的一个工具接口.那么" script "是啥? 字面上的意义, script 是"脚本.剧本"的意思.整句话是说,shell script 是针对 shell 所写的"剧本!"什么东西啊?其实

鸟哥的Linux私房菜——第十六章:学习Shell Scripts

视频链接: 1. 什么是 Shell Script       (shell写的脚本)1.1 干嘛学习 shell scripts? ()1.2 第一支 script 的撰写与执行1.3 撰写 shell script 的良好习惯建立 2. 简单的 shell script 练习: (read -p  date)3. 善用判断式:3.1 利用 test 指令的测试功能3.2 利用判断符号 [ ] 3.3 Shell script 的预设变数($0, $1...)4. 条件判断式:4.1 利用 i

Linux中shell scripts

▲shell脚本 shell script是利用shell的功能所写的一个程序,这个程序是使用纯文字文件,将一些shell语法与指令写在里面,搭配正则表达式,管道命令与数据流重导向等功能,以达到我们所想要的处理目的. shell script可以用来追踪与管理系统的重要工作,简单入侵侦测功能,建议的数据处理 ? 在shell script中需要注意的事项 指令与参数间的多个空白会被忽略掉 空白行和tab也将被忽略掉 如果读到一个Enter符号(CR),就尝试开始执行该命令 如果一行的内容太多,可

[Linux] Shell Scripts

shell script 是利用 shell 的功能所写的一个"程序 (program)",这个程序是使用纯文本文件,将一些 shell 的语法与指令(含外部指令)写在里面, 搭配正则表达式.管线命令与数据流重导向等功能,以达到我们所想要的处理目的 shell script 用在系统管理上面是很好的一项工具,但是用在处理大量数值运算上, 就不够好了,因为 Shell scripts 的速度较慢,且使用的 CPU 资源较多,造成主机资源的分配不良 在Shell script 的文件中,指

《跟老男孩学Linux运维之shell编程实战》-第三章 shell变量知识进阶

本文讲解shell变量知识进阶. 以下为知识点的总结,关于练习,本文不不涉及,还需要各位小伙伴自己练习! 1.shell中的特殊位置参数变量,请见下表: 在企业场景下,"$?"的用法: (1)判断命令.脚本或函数等程序是否执行成功: (2)若在脚本中调用执行"exit 数字",则会返回这个数字给"$?"变量: (3)如果是在函数里,则通过"return  数字",把这个数字以函数返回值的形式传给"$?".

第十三章、学习 Shell Scripts

1. 什么是 Shell Script 1.1 干嘛学习 shell scripts 1.2 第一支 script 的撰写与运行 1.3 撰写 shell script 的良好习惯创建 2. 简单的 shell script 练习 2.1 简单范例: 对谈式脚本, 随日期变化, 数值运算 2.2 script 的运行方式差异 (source, sh script, ./script) 3. 善用判断式 3.1 利用 test 命令的测试功能 3.2 利用判断符号 [ ] 3.3 Shell sc

清空系统日志shell scripts——自学笔记

这是一个清空系统日志的脚本: vim logmess_clean.sh #bin/bash        //该脚本所使用的shell解释器 cd /var/log/  //切换到存放日志目录 echo > messages  //清空日志 echo "logmessages is clean" //脚本执行完成后输出"日志清空" [[email protected] shellscripts]# ll    查看脚本的权限 total 4 -rw-r--r-