Skip to content

1 - Basic Bash Script

Shell Script

อ้างอิงจาก https://saixiii.com/basic-shell-script/

ตัวอย่าง Shell มี่นิยมใช้เขียน Shell script

Section titled “ตัวอย่าง Shell มี่นิยมใช้เขียน Shell script”

  • Bournr shell (/bin/sh) เป็น shell ในยุคแรกๆ ที่มีใช้กันอย่างแพร่หลาย มีการกำหนดโครงสร้างภาษาคล้ายๆ กับภาษาอัลกอ (Algo) สามารถเขียน shell script ได้ และยังเป็น starndard shell ที่มีใน UNIX ทุกตัว และยังสามารถย้าย shell script ไปยัง UNIX ระบบอื่นโดยไม่ต้องแก้ไขอะไรได้อีกด้วย จะมี default prompt เป็นเครื่องหมาย “ $ ”
  • C shell (/bin/csh) เป็น shell ที่พัฒนาขึ้นมาหลังจาก Bourne shell มีรูปแบบคำสั่งและไวยากรณ์เหมือนกับภาษา C มี function การทำงานหลายที่ดีและอย่างสะดวก อีกทั้งยังสามารถควบคุมการไหลของข้อมูลได้ดีกว่า Bourne shell และยังมีความสามารถในการเรียกใช้คำสั่งที่ใช้ไปแล้ว จะมี default prompt เป็นเครื่องหมาย “ % ”
  • Korn shell (/bin/ksh) เป็น shell ที่พัฒนามาจาดต้นแบบของ Bourne shell และ C shell สามารถทำงานใน function ของ Bourne shell ได้ทุกอย่าง การเขียน shell script ทำได้ง่ายและรัดกุมขึ้น สามารถนำคำสั่งที่ใช้ไปแล้วกลับมา execute ไปใหม่ได้ ถือได้ว่า Korn shell เป็นการรวมเอาข้อดีของ Bourne shell และ C shell มาไว้ด้วยกัน แต่ไม่ได้มีใน UNIX ทุกตัว จะมี default prompt เป็นเครื่องหมาย “ $ ”
  • Bournr again shell (/bin/bash หรือ /usr/local/bin/bash) เป็นการเอา Bournr shell นำกลับมาพัฒนาใหม่ สามารถทำงานแบบ line editing ได้ และยังได้เพิ่มประสิทธิภาพในการทำงานอีกหลายอย่าง bash shell นี้ไม่ใช่ standard UNIX shell แต่เป็น default shell ของ linux ในปัจจุบัน จะมี default prompt เป็นเครื่องหมาย “ $ ”
  1. Download VM: https://drive.google.com/file/d/1orBRMplTzVuRwuaUqhlXepndEIQiaEaJ/view?usp=sharing
  2. Import VM: Import VM
  3. Select OVA File: OVA File
  4. กด Finish: Finish OVA File
  5. รอ Import: Wait import
Terminal window
c@c:~$ poweroff
  1. Start VM: Start VM
  2. Open browser พิมพ์ http://localhost:8080 CODE SERVER
  3. ตอน shutdown VM ใช้คำสั่ง poweroff

Shell script เป็น file text ธรรมดาสามารถสร้างด้วย editor ชนิดไหนก็ได้ เช่น nano หรือ vim

Terminal window
nano ex1.sh

กำหนด interpreter หรือ shebang บรรทัดแรกของ shell script เราต้องกำหนด shebang เพื่อให้ program รู้ว่าควรใช้ interpreter ใดในการ load ข้อมูล file ซึ่งสัญลักษณ์ที่ใช้คือ #!<shell program>

  • #!/bin/sh
  • #!/bin/csh
  • #!/bin/bash
  • #!/bin/ksh
  • #!/usr/bin/perl
  • #!/usr/bin/env python

ใส่ชุดคำสั่ง command line ส่วนนี้คือ code program ที่เราต้องการให้ shell script ทำงาน ซึ่งสามารถศึกษาชุดคำสั่ง Shell ของ Unix และ Linux ได้

คำสั่งLinux
display/output textecho “hello world”
create filetouch a.txt
get contentcat a.txt
more a.txt
less a.txt
clear consoleclear
copy filecp a.txt b.txt
move filemv a.txt ../b.txt
delete filerm -i a.txt
list directoryls .
list all files (include hidden)ls -a
create directorymkdir my_folder
remove directoryrm -ri my_folder
change directorycd my_folder
ดู manual/help ของคำสั่งman ls

echo

touch

cat

clear

mkdir

cp

mv

rm

ls

rm

cd

man

กำหนดสิทธิ์ execute ให้กับ shell script หลักจากเราสร้าง Shell script ขึ้นมาได้แล้ว ลองสังเกตุจะเห็นว่า file ที่ได้มีสิทธิ์ หรือ permission ของ user owner (-rw-rw-r–) เพียงแค่ write กับ read เท่านั้น ไม่สามารถ execute ได้ ซึ่งก็ไม่ต่างกับ text file ธรรมดา

Terminal window
c@c:~/cos3105$ ls -ltr test.sh
-rw-r--r-- 1 c c 20 Jul 24 14:03 test.sh

ตอนจะรัน shell script ใช้คำสั่งดังนี้ แต่จากที่ผลลัพธ์คือรันไม่ได้

Terminal window
c@c:~/cos3105$ ./test.sh
bash: ./test.sh: Permission denied

ต้องเปลี่ยน permission ของไฟล์ให้สามารถรันได้ก่อนนั่นก็คือ

Terminal window
c@c:~/cos3105$ chmod 700 test.sh
c@c:~/cos3105$ ls -ltr test.sh
-rwx------ 1 c c 20 Jul 24 14:03 test.sh

ซึ่งเมื่อมีเครื่อง x แล้วนั้นหมายถึงเราสามารถ execute file นี้ได้แล้ว

Terminal window
c@c:~/cos3105$ ./test.sh
Hello COS3105

การสร้างตัวแปรใน shell script (variable) เชลล์สคริปต์เหมือนกับโปรแกรมทั่วๆไปที่มีตัวแปรไว้เก็บค่าต่างๆ สำหรับใช้งาน ตัวแปรที่ใช้ในเชลล์นั้นไม่จำเป็นต้องประกาศชนิดตัวแปรเหมือนกับภาษา C สามารถตั้งค่าแล้วนำไปใช้ได้ทันที

variable=value

#!/bin/bash
var1=Hello
var2=COS3105
var3='Hello COS3105'
var4="Hello COS3105"

การเรียกใช้งานตัวแปรใน shell script (variable) การเรียกใช้งานตัวแปรใน shell script (variable)

#!/bin/bash
var1=Hello
var2=COS3105
var3='Hello COS3105'
var4="Hello COS3105"
var5='$var1 $var2'
var6="$var1 $var2"
echo $var1
echo $var2
echo $var3
echo $var4
echo $var5
echo $var6

ซึ่งผลลัพธ์ที่ได้คือ เครื่องหมาย Quote ( ‘ ) จะมีค่าตามสิ่งที่พิมพ์ ส่วนในเครื่องหมาย Double quote ( “ ) จะเป็นการอ้างอิงนำผลลัพธ์ที่ตัวแปรเก็บไว้หรือค่าที่ตัวแปรเก็บไว้มาใช้

Terminal window
c@c:~/cos3105$ ./test.sh
Hello
COS3105
Hello COS3105
Hello COS3105
$var1 $var2
Hello COS3105

การใช้งานตัวแปร environment (environment variable) ตัวแปรที่ใช้ในเชลล์จะมีสองชนิดด้วยกัน คือ

  • ตัวแปรธรรมดา (variable)
  • ตัวแปรสภาพแวดล้อม (environment variable)
#!/bin/bash
echo $PWD
echo $USER

ซึ่งผลลัพธ์ที่ได้คือ $PWD คือ Print Working Directory

Terminal window
c@c:~/cos3105$ ./test.sh
/home/c/cos3105
c

ถ้าเราเรียกใช้ตัวแปรที่ไม่ได้อยู่ใน environment ผลลัพธ์ที่ได้จะมีค่าเป็น null

#!/bin/bash
echo $NAME

วิธีแก้คือ

Terminal window
c@c:~/cos3105$ export NAME="Krit Chomaitong"

หลังจากนั้น

Terminal window
c@c:~/cos3105$ ./test.sh
Krit Chomaitong

ตัวแปรแบบพิเศษ

ตัวแปรความหมาย
$0 $1 $2ใช้สำหรับอ้างอิงชื่อ shell script และ Argument ของ shell script เรียกว่า position parameter
$#ใช้บอกจำนวน Argument ที่อยู่ใน shell script นั้นๆ
$*แทน Argument ของ script เรียงกันทั้งหมด
$@คล้ายกับ $* แต่จะใช้ช่องว่างคั่นระหว่าง position parameter
$?ใช้แสดงสถานการณ์จบการทำงานครั้งสุดท้าย ถ้าสั่งได้ถูกต้องไม่มี error จะแสดงค่า 0 ออกมา แต่ถ้าผิดพลาดจะแสดงค่าที่ไม่ใช่ 0 ออกมา
$!ใช้แสดง process ID ของ shell ที่ทำงานอยู่
#!/bin/bash
echo $0 $1
Terminal window
c@c:~/cos3105$ ./test.sh hello world
./test.sh hello

$#

#!/bin/bash
echo $#
Terminal window
c@c:~/cos3105$ ./test.sh hello world
2
#!/bin/bash
echo $*
Terminal window
c@c:~/cos3105$ ./test.sh hello world aaa
hello world aaa
#!/bin/bash
echo $@
Terminal window
c@c:~/cos3105$ ./test.sh hello world aaa
hello world aaa
#!/bin/bash
echo "hello"
echo $?
Terminal window
c@c:~/cos3105$ ./test.sh
hello
0
#!/bin/bash
# ต้องใช้ long process อย่าง sleep ถึงจะบอกได้ว่า process ID คืออะไร
sleep 30 & echo $!
Terminal window
c@c:~/cos3105$ ./test.sh
14213

ใช้เครื่องหมาย # สำหรับการ comment (ยกเว้นบรรทัดแรกเพราะเป็น shebang)

#!/bin/bash
# Test Comment
var=hello
echo $var

จากผลลัพธ์ที่ได้ โปรแกรมจะไม่แสดงบรรทัดที่ comment ออกมา

Terminal window
c@c:~/cos3105$ ./test.sh
hello
#!/bin/bash
txt[0]="a"
txt[1]="b"
txt[2]="c"
echo $txt[0] $txt[1] $txt[2]
echo ${txt[0]} ${txt[1]} ${txt[2]}

ผลลัพธ์ที่ได้

Terminal window
c@c:~/cos3105$ ./test.sh
a[0] a[1] a[2]
a b c
#!/bin/bash
result=$(ls)
echo $result

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
bio.db bio.txt cron.log email.sh lab2-2.sh lab2.sh test.bak test.sh
  • ใช้ $(()) หรือ let ก็ได้
#!/bin/bash
a=1
b=0
c=$((a/b))
echo $c
b=2
let c=a*b
echo $c

OUTPUT

Terminal window
./test.sh: line 3: a/b: division by 0 (error token is "b")
2
#!/bin/bash
int1=1
int2=2
int3=1
if [ "$int1" -eq "$int3" ]
then
echo "$int1 equal $int3"
fi
if [ "$int1" -ne "$int2" ]
then
echo "$int1 not equal $int2"
fi
if [ "$int2" -gt "$int1" ]
then
echo "$int2 greater than $int1"
fi
if [ "$int2" -ge "$int1" ]
then
echo "$int2 greater than or equal $int1"
fi
if [ "$int1" -lt "$int2" ]
then
echo "$int1 less than $int2"
fi
if [ "$int1" -le "$int2" ]
then
echo "$int1 less than or equal $int2"
fi

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
1 equal 1
1 not equal 2
2 greater than 1
2 greater than or equal 1
1 less than 2
1 less than or equal 2
#!/bin/bash
str1="Hello"
str2="Hello"
str3="World"
str4=" "
str5=""
if [ "$str1" = "$str2" ]
then
echo "$str1 equal $str2"
fi
if [ "$str2" != "$str3" ]
then
echo "$str1 not equal $str3"
fi
if [ -n "$str4" ]
then
echo "$str4 is not empty"
fi
if [ "$str4" ]
then
echo "$str4 contains space"
fi
if [ !"$str5" ]
then
echo "$str5 is empty"
fi
if [ -z "$str5" ]
then
echo "$str5 is also empty"
fi

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Hello equal Hello
Hello not equal World
is not empty
contains space
is empty
is also empty
#!/bin/bash
folderName="folder2"
fileName="bio.txt"
if [ -d "$folderName" ]
then
echo "$folderName is a folder"
fi
if [ -f "$fileName" ]
then
echo "$fileName is a file"
fi
if [ -r "$fileName" ]
then
echo "$fileName is readable"
fi
if [ -w "$fileName" ]
then
echo "$fileName is writable"
fi
if [ -x "$fileName" ]
then
echo "$fileName is executable"
fi
if [ -s "$fileName" ]
then
echo "$fileName is not empty"
fi

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
folder2 is a folder
bio.txt is a file
bio.txt is readable
bio.txt is writable
bio.txt is not empty
  • && คือ and ต้องใช้ภายใต้ [[…]]
  • || คือ or ต้องใช้ภายใต้ [[…]]
#!/bin/bash
a=5
b=10
if [[ $a -lt 10 && $b -gt 5 ]]; then
echo "Both conditions are true"
fi
if [[ $a -lt 5 || $b -gt 5 ]]; then
echo "At least one condition is true"
fi
#!/bin/bash
a=5
b=10
if [ "$a" -eq "$b" ]; then
echo "$a equals $b"
else
echo "$a not equals $b"
fi
if [ "$a" -eq "$b" ]; then
echo "$a equals $b"
elif [ $((a * 2)) -eq "$b" ]; then
echo "$a * 2 equals $b"
fi

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
5 not equals 10
5 * 2 equals 10
  • รูปแบบคำสั่ง
Terminal window
case string in
str1)
commands;;
str2)
commands;;
str3)
commands;;
*)
commands;;
esac

ตัวอย่าง

#!/bin/bash
var1="cat"
case $var1 in
"ant")
echo "It is an ant";;
"bee")
echo "It is an bee";;
"cat")
echo "It is an cat";;
*)
echo "I don't know";;
esac

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
It is an cat
  • รูปแบบคำสั่ง
Terminal window
while [ expression ]
do
commands
………….
done

ตัวอย่าง

#!/bin/bash
num=1
while [ $num -le 5 ]
do
echo "Loop $num"
((num = $num+1))
done

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
  • รูปแบบคำสั่ง
Terminal window
for var in list
do
commands
………….
done

ตัวอย่าง1

#!/bin/bash
for i in 1 2 3 4 5
do
echo "Loop $i"
done

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5

ตัวอย่าง2

#!/bin/bash
for ((i=1;i<5;i++))
do
echo "Loop $i"
done

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Loop 1
Loop 2
Loop 3
Loop 4

การรับค่า input จาก script

Section titled “การรับค่า input จาก script”
#!/bin/bash
var0=$0
var1=$1
var2=$2
echo "$0, $1 , $2"

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh 1 2
./test.sh , 1 , 2
  • output redirection
คำสั่งความหมาย
echo "Hello" > file.txtWrite output to file.txt (overwrite)
echo "Hello" >> file.txtAppend output to file.txt
  • input redirection
คำสั่งความหมาย
cat < file.txtRead from file.txt

การรับค่าจาก Keyboard

Section titled “การรับค่าจาก Keyboard”
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Enter your name:
Krit
Hello, Krit!
  • grep = “global regular expression print”
  • ดึงค่า name:
bio.txt
name: Krit Chomaitong
birth date: 22/10/1999
address: 123 Maplewood Lane, Fairview, CA 90210, USA

OUTPUT

Terminal window
c@c:~/cos3105$ grep "name: " bio.txt
name: Krit Chomaitong

การใช้ cut ร่วมกับ grep

Section titled “การใช้ cut ร่วมกับ grep”
#!/bin/bash
cut -d':' -f2- bio.txt # -d for single character
grep "^name:" bio.txt | cut -d':' -f2- # grep with cut

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Krit Chomaitong
22/10/1999
123 Maplewood Lane, Fairview, CA 90210, USA
Krit Chomaitong
  • ค้นหา name:
#!/bin/bash
sed -n 's/^name:\(.*\)/\1/p' bio.txt

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Krit Chomaitong
  • การอัพเดต name:
#!/bin/bash
sed -i 's/^name:.*/name:Krit Chomaitong2/' bio.txt # update
sed -n 's/^name:\(.*\)/\1/p' bio.txt # print match name:

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Krit Chomaitong2

การใช้ history ร่วมกับ grep

Section titled “การใช้ history ร่วมกับ grep”
Terminal window
history

OUTPUT

Terminal window
c@c:~/cos3105$ history
1 curl -fsSL https://code-server.dev/install.sh | sh
2 sudo apt install neovim build-essential gcc g++ gdb
3 python
  • การใช้ร่วมกับ grep โดยใช้ pipe
Terminal window
history | grep cat

OUTPUT

Terminal window
c@c:~/cos3105$ history | grep cat
63 cat output.txt
67 cat cron.log
71 cat cron.log
76 cat output.txt
79 cat cron.log
#!/bin/bash
d=$(date)
echo $d
echo "$(date)"
echo $(date)
echo "`date`"
date

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
Sun Aug 3 01:39:36 PM UTC 2025
Sun Aug 3 01:39:36 PM UTC 2025
Sun Aug 3 01:39:36 PM UTC 2025
Sun Aug 3 01:39:36 PM UTC 2025
Sun Aug 3 01:39:36 PM UTC 2025
  • format date
Formatความหมายตัวอย่าง
%Yปี (4 หลัก)2025
%yปี (2 หลัก)25
%mเดือน (01-12)08
%dวัน (01-31)03
%Hชั่วโมง (00–23)19
%Mนาที (00–59)50
%Sวินาที (00–59)00
%Aชื่อวัน (เต็ม)Sunday
%aชื่อวัน (ย่อ)Sun
%Bชื่อเดือน (เต็ม)August
%bชื่อเดือน (ย่อ)Aug

ตัวอย่าง

#!/bin/bash
date +"%Y-%m-%d"
date +"%Y-%m-%d %H:%M:%S"
date -d "tomorrow" +"%Y-%m-%d" # tomorrow

OUTPUT

Terminal window
c@c:~/cos3105$ ./test.sh
2025-08-03
2025-08-03 13:43:25
2025-08-04

แหล่งอ้างอิง