สรุปสิ่งที่ควรรู้
- ใช้คำสั่ง cd เพื่อเปลี่ยน Current Working Directory ใช้ pwd เพื่อตรวจสอบ Directory ปัจจุบัน
- ใช้ / (Forward Slash) เพื่อไป Root Directory ใช้ - (Hyphen) เพื่อไป Directory ก่อนหน้า
- ใช้ ~ (Tilde) เพื่อไป User Home Directory
บทความนี้อธิบายวิธีเปลี่ยน Directory ใน Linux ใช้ได้กับทุก Distribution
Working Directories ใน Linux
คำสั่ง cd ของ Linux ใช้เปลี่ยน Current Directory ใช้เวลาทำงานใน Shell Session (เช่นเปิด Terminal จาก Graphical Desktop) เพื่อเปลี่ยน Current Working Directory
เวลาใช้ Linux ในสภาพแวดล้อม Graphical นานๆ ไม่คิดถึง Current Working Directory มาก แต่เวลาทำงานใน Shell ระบบจะถือว่า Scope ของการทำงานคือ Current Directory เว้นแต่จะระบุอื่นออกไป ตัวอย่าง: เวลาเซฟไฟล์ใน LibreOffice Writer จะ Default ไปที่ Home Directory แต่เวลาเซฟไฟล์ด้วย Text Editor ใน Shell จะ Default ไปที่ Current Working Directory
เพื่อเช็คว่าอยู่ Directory ไหน ใช้คำสั่ง pwd จะพิมพ์ Working Directory ออกมาที่ Standard Output (เพราะฉะนั้นชื่อคำสั่งจึงเป็น pwd)
วิธีใช้คำสั่ง 'CD' เปลี่ยน Current Working Directory
คำสั่ง cd เรียบง่ายขั้นสุด:
cd [directory]
คำสั่งนี้มี Options เพียง 2 ตัว ซึ่งใช้บ่อย:
- -P: ใช้ Physical Directory Structure ไม่สน Symbolic Links
- -L: บังคับให้ Follow Symbolic Links
Local และ Absolute Pathnames ในคำสั่ง 'CD'
ใช้ Absolute Pathnames หรือ Local Pathnames กับคำสั่ง cd ได้ Absolute Pathname เริ่มจาก Root Directory ส่วน Local Pathname เป็น Relative เทียบกับ Current Working Directory
เช่น ถ้าอยู่ที่ /var/www/html แต่ต้องการไป /var/www/html/img ทั้งสองคำสั่งนี้ได้ผลเหมือนกัน:
cd /var/www/html/img cd img
Shortcuts สำหรับนำทางใน Filesystem
ใช้ Shortcuts ต่อไปนี้กับคำสั่ง cd:
- /: ไป Root Directory (Forward Slash)
- ..: ไป Parent Directory (จุดสองตัวติดกัน)
- ~: ไป Home Directory ของ User ที่ Login (Tilde)
- -: ไป Previous Directory (Hyphen)
ขึ้นอยู่กับ Shell ที่ใช้ อาจเห็น Shortcut Symbol ต่อท้าย Username ที่ Prompt หรือชื่อ Current Directory
ปัญหา Permissions
ใน Linux ไฟล์และ Directory ทั้งคู่มี Permissions โดยทั่วไป ไฟล์/โฟลเดอร์ใดๆ อาจ Readable, Writable, หรือ Executable ได้ ขึ้นอยู่กับว่าคุณเป็น Owner, อยู่ใน Group ที่มีสิทธิ์ หรือเป็น Global User
หากพยายามเปลี่ยนไป Directory ที่ไม่มีสิทธิ์อ่าน จะได้ Error ตัวอย่าง: User ธรรมดาใน Bash Shell พยายามเข้า /root จะได้ Error:
bash: cd: /root: Permission denied
แก้ได้โดย: ใช้สิทธิ์ขlevated (เช่นคำสั่ง sudo) หรือเปลี่ยน Permissions ของ Directory ด้วยคำสั่ง chmod
บทความแนะนำ: The Power of the 'Sudo' Command | How to Use the 'Chmod' Linux Command