การเขียนโปรแกรม shell ใน Linux

จาก Research 2549, สารานุกรมฟรี

<<Back

สารบัญ

การส่งข้อมูลระหว่าง shell กับโปรแกรม

  • ตัวแปรที่ส่งเข้าโปรแกรมสามารถอ่านเข้ามาได้ผ่าน $1, $2, $3, ....

ยกตัวอย่าง shell โปรแกรม test.sh

#!/bin/bash
echo Zero = $0
echo One = $1
echo Two = $2
echo Three = $3

ทดสอบโปรแกรมด้วยคำสั่ง

prachya@fujitablet:~/it4502$ sh test.sh home sweet home
Zero = test.sh
One = home
Two = sweet
Three = home

หากเราต้องการทำให้สคริปต์สามารถรันได้โดยไม่ต้องเรียก sh ให้เปลี่ยน mode ของโปรแกรมให้เป็น 755

chmod 755 test.sh
./test.sh home sweet home

ก็จะสามารถรันโปรแกรมได้ด้วยการเรียกตรง ๆ

พื้นฐานของโปรแกรมที่รันใน shell

  • ถ้ายังไม่มีโปรแกรมคอมไพล์เลอร์ gcc ให้ติดตั้ง (Ubuntu) ด้วยคำสั่ง
sudo apt-get install gcc
sudo aptitude install build-essential
  • จากนั้นสามารถคอมไพล์โปรแกรมภาษา C/C++ ด้วยคำสั่ง
gcc myprogram.c

หรือ

gcc -o mybin myprogram.c

โดยที่ -o mybin เป็นการบอกให้สร้างไบนารี่ไฟล์ที่สามารถรันได้ให้เป็นชื่อ mybin

  • ตัวอย่างโปรแกรมภาษาซี ที่ใช้รันใน shell ให้ใช้ vi หรือ pico เพื่อสร้างโปรแกรมนี้ขึ้นมา
vi test1.c

ซึ่งมีคำสั่งต่าง ๆ ดังต่อไปนี้

#include<stdio.h>
main(){
  char buff[128];
  int count=0;
  while(!feof(stdin)) {
    fscanf(stdin,"%s",buff);
    fprintf(stdout,"%d - %s\n",count++,buff);
  }
}

จากนั้นคอมไพล์ด้วย gcc จะได้ไบนารีไฟล์ชื่อ a.out

gcc test1.c

จากนั้นให้ทดลองรันโปรแกรม เพื่อทดสอบการส่งข้อมูลเข้าไปยังโปรแกรม

prachya@fujitablet:~/it4502$ head -5 /etc/passwd | ./a.out
0 - root:x:0:0:root:/root:/bin/bash
1 - daemon:x:1:1:daemon:/usr/sbin:/bin/sh
2 - bin:x:2:2:bin:/bin:/bin/sh
3 - sys:x:3:3:sys:/dev:/bin/sh
4 - sync:x:4:65534:sync:/bin:/bin/sync
5 - sync:x:4:65534:sync:/bin:/bin/sync

การเขียนโปรแกรมใน shell เบื้องต้น

ตัวแปรในเชลล์สคริปท์

การใช้ for ในเชลล์สคริปท์

 for i in 01 02 03 cat dog hat rat; do
   echo $i
 done

การใช้ while

 x=1
 while (( x < 10 )); do
   echo $x
   (( x = x + 1 ))
 done

Execise and Test Data

  • เขียน shell script เพื่อนับจำนวนว่า เครื่อง IP ใดมีจำนวนการ access มากที่สุด
  • เขียน shell script เพื่อตรวจสอบดูว่า URL ใดมีการใช้งานมากที่สุด
  • ใช้ข้อมูล Squid Log ที่ ftp://nis.crma/pub/public/test-data.log
 cut -d' ' -f 7 test-data.log > ip-list4
 grep '10.134' ip-list4 > ip-list4a

สร้าง shell script เพื่อนับจำนวน

crma@crma-desktop:~/exercise1$ cat chk-ip.sh
x=0
y=0
while (( x < 256 )); do
   while (( y < 256 )); do
         z=$(grep 10.134.$x.$y ip-list4a | wc -l)
         echo 10.134.$x.$y $z
         (( y = y + 1 ))
   done
   (( y = 0 ))
   (( x = x + 1 ))
done

References

Personal tools