5. ตัวแปร (Variables)

ตัวแปรในเชลล์สคริปต์ ไม่มีชนิดข้อมูล คือเราสามารถใช้ตัวแปรแทนตัวเลขหรืออักขระใด ๆ ก็ได้
โดยในขั้นตอนกำหนดค่า ไม่ต้องใช้เครื่องหมายใด ๆ นำหน้า แต่ตอนอ้างถึง ต้องใช้เครื่องหมาย $ นำหน้าตัวแปร

5.1 ตัวอย่างสคริปต์ Hello World แบบใช้ตัวแปร

#!/bin/bash          
STR="Hello World!"
echo $STR

ให้ผลลัพธ์เหมือนตัวอย่างที่ 2.1

ข้อควรระวังคือ

  • การกำหนดค่าให้ตัวแปร อย่าเว้นวรรคระหว่างตัวแปรกับเครื่องหมาย =
  • หากลืมใส่เครื่องหมาย $ จะหมายถึงการแสดงผลข้อความว่า STR เฉย ๆ

5.2 ตัวอย่างสคริปต์สำรองข้อมูลแบบใช้ตัวแปร

#!/bin/bash          
OF=/tmp/my-backup-$(date +%Y%m%d).tgz
tar -cvzf $OF /home/USER/

ให้ผลลัพธ์คล้ายตัวอย่าง 2.2 แต่เพิ่มการใช้ตัวแปรลอยในคำสั่ง $(date +%Y%m%d) ซึ่งมีผลทำให้ชื่อไฟล์ข้อมูลสำรองมีวันที่ต่อท้ายชื่อด้วย

5.3 ตัวแปรท้องถิ่น

ตัวแปรในเชลล์สคริปต์ทุกตัว จะเป็นตัวแปรรวม (Global) คือทุก ๆ ส่วนของโปรแกรมจะเห็นเหมือนกันหมด

แต่ในกรณีที่เราต้องการให้เห็นเฉพาะในฟังก์ชั่นที่เราต้องการ เราสามารถกำหนดให้ตัวแปรเป็นตัวแปรท้องถิ่นได้ด้วยคำสั่ง local

เช่น

#!/bin/bash
HELLO=Hello 
function hello {
        local HELLO=World
        echo $HELLO
}

echo $HELLO
hello
echo $HELLO

สคริปต์นี้ตัวแปร HELLO ในโปรแกรมหลัก กับในฟังก์ชั่นจะเป็นตัวแปรคนละตัวกัน

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <blockquote> <img> <h3> <h4> <h5>
  • Lines and paragraphs break automatically.
  • E-Mail addresses are hidden with reCAPTCHA Mailhide.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.