Daftar Isi
Saya rasa belajar sistem komputer seperti belajar bahasa asing baru. Meskipun buku dan dokumentasi tutorial sangat membantu, Anda harus mempraktikkannya sendiri. Untuk membantu Anda memulai dengan lancar, saya menguraikan beberapa hal mendasar.
Desain kuat dari Debian GNU/Linux berasal dari sistem operasi Unix, yaitu, suatu sistem operasi yang multiuser, multitasking. Anda harus belajar untuk mengambil keuntungan dari kekuatan fitur-fitur ini dan kemiripan antara Unix dan GNU/Linux.
Jangan menghindar dari teks yang berorientasi Unix dan jangan hanya mengandalkan teks GNU/Linux, karena ini merampas banyak informasi berguna.
![]() |
Catatan |
---|---|
Jika Anda telah menggunakan salah satu sistem mirip Unix untuk sementara waktu dengan baris perintah, Anda mungkin tahu segala sesuatu yang saya jelaskan di sini. Harap gunakan ini sebagai uji realita dan penyegaran. |
Saat memulai sistem, Anda disajikan layar login berbasis karakter bila Anda
tidak memasang lingkungan GUI seperti misalnya
sistem desktop GNOME atau KDE. Misalnya nama host Anda adalah
foo
, sapaan login tampak sebagai berikut.
Bila Anda memasang suatu lingkungan GUI , maka Anda masih dapat menuju ke sapaan login berbasis karakter dengan Ctrl-Alt-F3, dan Anda dapat kembali ke lingkungan GUI melalui Ctrl-Alt-F2 (lihat Bagian 1.1.6, “Konsol virtual” di bawah untuk lebih lanjut).
foo login:
Pada sapaan login, Anda mengetikkan nama pengguna Anda,
mis. penguin
, dan menekan tombol Enter, lalu ketikkan
password Anda dan tekan tombol Enter lagi.
![]() |
Catatan |
---|---|
Mengikuti tradisi Unix, username dan password sistem Debian membedakan huruf
besar kecil. Nama pengguna biasanya dipilih hanya dari huruf kecil. Akun
pengguna pertama biasanya dibuat saat instalasi. Akun pengguna tambahan
dapat dibuat dengan |
Sistem mengawali dengan pesan sapaan yang disimpan dalam
"/etc/motd
" (Message Of The Day, Pesan Hari Ini) dan
menyajikan suatu sapaan perintah.
Debian GNU/Linux 11 foo tty1 foo login: penguin Password: Linux foo 5.10.0-6-amd64 #1 SMP Debian 5.10.28-1 (2021-04-09) x86_64 The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Thu May 13 08:47:13 JST 2021 on tty1 foo:~$
Sekarang Anda berada di shell. Shell menafsirkan perintah-perintah Anda.
Jika Anda menginstal lingkungan GUI selama instalasi, Anda akan disajikan dengan layar login grafis saat memulai sistem Anda. Anda mengetikkan nama pengguna dan kata sandi Anda untuk log masuk ke akun pengguna biasa. Gunakan tab untuk menavigasi antara nama pengguna dan kata sandi, atau gunakan klik primer tetikus.
You can gain the shell prompt under GUI environment by starting a
x-terminal-emulator
program such as
gnome-terminal
(1), rxvt
(1) or
xterm
(1). Under the GNOME Desktop environment, press
SUPER-key (Windows-key) and typing in "terminal" to the search prompt does
the trick.
Di bawah beberapa sistem Desktop lain (seperti fluxbox
),
mungkin ada titik awal yang jelas untuk menu. Jika ini terjadi, cobalah
mengklik (kanan) latar belakang layar desktop dan berharap untuk munculnya
suatu menu.
Akun root juga disebut superuser atau pengguna istimewa. Dari akun ini, Anda dapat melakukan tugas-tugas administrasi sistem berikut.
Baca, tulis, dan hapus file apapun di sistem terlepas dari hak akses file mereka
Setel kepemilikan file dan hak akses file apapun pada sistem
Tetapkan kata sandi pengguna non-istimewa di sistem
Login ke akun manapun tanpa password mereka
Kekuatan akun root tak terbatas ini mengharuskan Anda untuk mempertimbangkan dan bertanggung jawab saat menggunakannya.
![]() |
Awas |
---|---|
Jangan pernah berbagi password root dengan yang lain. |
![]() |
Catatan |
---|---|
Izin dalam sebuah berkas (termasuk perangkat keras seperti dll. CD-ROM yang sekedar suatu berkas lain untuk sistem Debian) dapat membuatnya tidak dapat digunakan atau tidak dapat diakses oleh pengguna non-root. Meskipun penggunaan akun root adalah cara cepat untuk menguji situasi semacam ini, resolusi harus dilakukan melalui pengaturan hak akses berkas dan keanggotaan grup pengguna yang tepat (Lihat Bagian 1.2.3, “Hak akses Filesystem”). |
Berikut adalah beberapa metode dasar untuk mendapatkan root shell prompt dengan menggunakan password root.
Ketikkan root
pada prompt login mode teks.
Ketik "su -l
" dari sebarang prompt shell pengguna.
Ini tidak mempertahankan lingkungan pengguna saat ini.
Ketik "su -l
" dari sebarang prompt shell pengguna.
Ini mempertahankan sebagian lingkungan pengguna saat ini.
Ketika menu desktop Anda tidak memulai alat administrasi sistem GUI secara
otomatis dengan hak istimewa yang sesuai, Anda dapat memulai mereka dari
prompt shell root dari emulator terminal, seperti
gnome-terminal
(1), rxvt
(1), atau
xterm
(1). Lihat Bagian 1.1.4, “Prompt shell root”
dan Bagian 7.8, “X server connection”.
![]() |
Awas |
---|---|
Jangan pernah memulai pengelola tampilan/sesi GUI di bawah akun root dengan
mengetikkan Jangan pernah menjalankan program GUI remote tidak terpercaya di bawah X Window ketika informasi penting ditampilkan karena itu dapat menguping X layar Anda. |
Dalam sistem Debian default, ada enam konsol mode teks mirip VT100 yang dapat ditukar, tersedia untuk
memulai shell perintah langsung pada host Linux. Kecuali Anda berada di
lingkungan GUI, Anda dapat beralih antara konsol virtual dengan menekan
tombol Alt kiri
dan salah satu tombol
F1
-F6
secara bersamaan. Setiap konsol
mode teks memungkinkan login yang independen ke akun dan menawarkan
lingkungan multiuser. Lingkungan multiuser ini adalah fitur Unix yang
hebat, dan sangat adiktif.
Jika Anda berada dalam lingkungan GUI, Anda mendapatkan akses ke konsol mode
teks 3 dengan menekan tombol Ctrl-Alt-F3
, yaitu
tombol Ctrl kiri
, tombol Alt kiri
, dan
tombol F3
ditekan bersamaan. Anda dapat bisa kembali ke
lingkungan GUI, biasanya berjalan pada konsol virtual 2, dengan menekan
Alt-F2
.
Anda juga dapat berpindah ke konsol virtual lain, mis. ke konsol 3, dari baris perintah.
# chvt 3
Anda mengetik Ctrl-D
, yaitu tombol Ctrl
kiri
dan tombol d
ditekan bersama-sama, pada
prompt perintah untuk menutup kegiatan shell. Jika Anda berada pada konsol
mode teks, Anda kembali ke prompt login dengan ini. Meskipun karakter
kontrol ini disebut sebagai "kontrol D" dengan huruf besar, Anda tidak perlu
menekan tombol Shift. Ekspresi singkat, ^D
, juga
digunakan untuk Ctrl-D
. Sebagai alternatif, Anda dapat
mengetikkan "exit".
Jika Anda di x-terminal-emulator
(1), Anda bisa menutup
jendela x-terminal-emulator
dengan ini.
Sama seperti OS moden lain manapun dimana operasi berkas melibatkan penyinggahan data dalam memori untuk peningkatan kinerja, sistem Debian memerlukan prosedur shutdown yang tepat sebelum daya aman dimatikan. Ini adalah untuk mempertahankan integritas berkas, dengan memaksa semua perubahan dalam memori harus ditulis ke disk. Jika perangkat lunak kendali daya tersedia, prosedur shutdown secara otomatis mematikan daya sistem. (Jika tidak, Anda mungkin harus menekan tombol power selama beberapa detik setelah prosedur shutdown.)
Anda bisa mematikan sistem di bawah mode multi user normal dari command line.
# shutdown -h now
Anda bisa mematikan sistem di bawah mode single-user dari commandline.
# poweroff -i -f
Lihat Bagian 6.3.8, “How to shutdown the remote system on SSH”.
Ketika layar mengamuk setelah melakukan beberapa hal lucu seperti
"cat suatu-berkas-biner
", ketikkan
"reset
" pada prompt perintah. Anda mungkin tidak dapat
melihat perintah dipantulkan saat Anda mengetik. Anda dapat juga
memerintahkan "clear
" untuk membersihkan layar.
Meskipun instalasi minimal sistem Debian tanpa task lingkungan desktop apa
pun telah menyediakan fungsionalitas dasar Unix, ide yang baik untuk
menginstal beberapa perintah tambahan dan paket terminal karakter berbasis
curses seperti mc
dan vim
dengan
apt-get
(8) bagi pemula untuk mengawali dengan yang
berikut ini.
# apt-get update ... # apt-get install mc vim sudo ...
Jika Anda sudah menginstal paket ini, tidak ada paket baru yang diinstal.
Tabel 1.1. Daftar paket program mode teks yang menarik
paket | popcon | ukuran | deskripsi |
---|---|---|---|
mc
|
V:55, I:234 | 1492 | Manajer berkas layar penuh mode teks |
sudo
|
V:597, I:809 | 4589 | Sebuah program untuk mengizinkan hak istimewa root terbatas kepada pengguna |
vim
|
V:102, I:404 | 3286 | Editor teks Unix Vi IMproved, editor teks pemrogram (versi standar) |
vim-tiny
|
V:57, I:969 | 1574 | Editor teks Unix, Vi IMproved, editor teks programmer (versi ringkas) |
emacs-nox
|
V:4, I:19 | 18364 | Proyek GNU Emacs, penyunting teks yang dapat diperluas berbasis Lisp |
w3m
|
V:25, I:252 | 2367 | Peramban WWW mode teks |
gpm
|
V:11, I:16 | 540 | Potong dan tempel gaya Unix pada konsol mode teks (daemon) |
Mungkin ada baiknya membaca beberapa dokumentasi informatif.
Tabel 1.2. Daftar paket dokumentasi informatif
paket | popcon | ukuran | deskripsi |
---|---|---|---|
doc-debian
|
I:850 | 166 | Dokumentasi Proyek Debian, (FAQ Debian) dan dokumen lainnya |
debian-policy
|
I:29 | 4306 | Manual Kebijakan Debian dan dokumen terkait |
developers-reference
|
I:6 | 1916 | Panduan dan informasi untuk pengembang Debian |
debmake-doc
|
I:0 | 10989 | Panduan untuk Pengelola Debian |
debian-history
|
I:1 | 4285 | Sejarah Proyek Debian |
debian-faq
|
I:846 | 817 | FAQ Debian |
Anda dapat menginstal beberapa paket berikut ini.
# apt-get install package_name
Jika Anda tidak ingin menggunakan akun pengguna utama untuk kegiatan
pelatihan berikut, Anda dapat membuat akun pengguna pelatihan, misalnya
fish
dengan cara berikut.
# adduser fish
Jawablah semua pertanyaan.
Ini membuat akun baru bernama fish
. Setelah latihan
Anda, Anda dapat menghapus akun pengguna ini dan direktori home-nya dengan
cara berikut.
# deluser --remove-home fish
Untuk workstation pengguna tunggal biasa seperti sistem Debian desktop pada
PC laptop, biasanya menggunakan konfigurasi sederhana
sudo
(8) sebagai berikut untuk membiarkan pengguna yang
tidak memiliki hak istimewa, mis. penguin
, untuk
mendapatkan hak administratif hanya dengan kata sandi penggunanya tetapi
tanpa kata sandi root.
# echo "penguin ALL=(ALL) ALL" >> /etc/sudoers
Sebagai alternatif, juga biasa dilakukan sebagai berikut untuk membiarkan
pengguna biasa, mis. penguin
, untuk mendapatkan hak
administratif tanpa kata sandi.
# echo "penguin ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
Trik ini hanya boleh digunakan untuk workstation pengguna tunggal yang Anda kelola dan di mana Anda adalah satu-satunya pengguna.
![]() |
Awas |
---|---|
Jangan membuat akun pengguna biasa di workstation multiuser seperti ini karena akan sangat buruk bagi keamanan sistem. |
![]() |
Perhatian |
---|---|
Kata sandi dan akun Hak administratif dalam konteks ini adalah milik seseorang yang berwenang untuk melakukan tugas administrasi sistem pada workstation. Jangan pernah memberikan hak semacam itu kepada manajer di departemen Admin di perusahaan Anda atau bos Anda, kecuali mereka memiliki wewenang dan kemampuan. |
![]() |
Catatan |
---|---|
Untuk memberikan hak akses ke perangkat terbatas dan berkas terbatas, Anda
mesti mempertimbangkan untuk menggunakan group untuk memberikan akses terbatas daripada
menggunakan hak istimewa Dengan konfigurasi yang lebih bijaksana dan hati-hati,
|
Sekarang Anda siap untuk bermain dengan sistem Debian tanpa risiko selama Anda menggunakan akun pengguna yang tidak memiliki hak istimewa.
Ini karena sistem Debian, bahkan setelah instalasi baku, dikonfigurasi dengan izin berkas yang tepat yang mencegah pengguna yang tidak memiliki hak istimewa merusak sistem. Tentu saja, mungkin masih ada beberapa lubang yang dapat dieksploitasi tetapi mereka yang khawatir tentang masalah ini tidak boleh membaca bagian ini tetapi harus membaca Manual Mengamankan Debian.
Kami mempelajari sistem Debian sebagai sebuah sistem mirip Unix dengan yang berikut ini.
Bagian 1.2, “Sistem berkas mirip Unix” (konsep dasar)
Bagian 1.3, “Midnight Commander (MC)” (metode survival)
Bagian 1.4, “The basic Unix-like work environment” (metode dasar)
Bagian 1.5, “The simple shell command” (mekanisme shell)
Bagian 1.6, “Unix-like text processing” (metode pengolahan teks)
Di GNU/Linux dan sistem operasi mirip Unix
lainnya, berkas diatur ke dalam direktori. Semua berkas dan direktori diatur
dalam satu pohon besar yang berakar pada "/
". Disebut
pohon karena jika Anda menggambar sistem berkas, itu terlihat seperti pohon
tetapi terbalik.
Berkas dan direktori ini dapat tersebar di beberapa
perangkat. mount
(8) berfungsi untuk mencantolkan sistem
berkas yang ditemukan pada beberapa perangkat ke pohon berkas besar.
Sebaliknya, umount
(8) melepaskannya lagi. Pada kernel
Linux terbaru, mount
(8) dengan beberapa opsi dapat
mengikat bagian dari pohon berkas di tempat lain atau dapat mengait sistem
berkas sebagai shared, private, slave, atau unbindable. Opsi pemasangan yang
didukung untuk setiap sistem berkas tersedia di
"/usr/share/doc/linux-doc-*/Documentation/filesystems/
".
Direktori pada sistem Unix disebut
folder pada beberapa sistem lain. Harap
perhatikan juga bahwa tidak ada konsep untuk drive seperti "A:
" pada sistem
Unix mana pun. Ada satu sistem berkas, dan semuanya disertakan. Ini adalah
keuntungan besar dibandingkan dengan Windows.
Berikut adalah beberapa dasar-dasar file Unix.
Nama berkas peka huruf besar/kecil.
Artinya, "MYFILE
" dan "MyFile
" adalah
berkas yang berbeda.
Direktori root berarti akar dari sistem
berkas yang disebut sebagai "/
". Jangan bingung dengan
direktori home untuk pengguna root: "/root
".
Setiap direktori memiliki nama yang dapat berisi huruf atau simbol kecuali "/
". Direktori root
adalah pengecualian; namanya adalah "/
" (diucapkan
"slash" atau "direktori root") dan tidak dapat diganti namanya.
Setiap berkas atau direktori ditunjuk oleh fully-qualified filename, nama berkas absolut, atau path, memberikan urutan direktori yang harus dilalui untuk mencapainya . Ketiga istilah tersebut sinonim.
All fully-qualified filenames begin with
the "/
" directory, and there's a "/
"
between each directory or file in the filename. The first
"/
" is the top level directory, and the other
"/
"'s separate successive subdirectories, until we reach
the last entry which is the name of the actual file. The words used here
can be confusing. Take the following fully-qualified filename as an example:
"/usr/share/keytables/us.map.gz
". However, people also
refers to its basename "us.map.gz
" alone as a filename.
Direktori root memiliki sejumlah cabang, seperti "/etc/
"
dan "/usr/
". Subdirektori ini pada gilirannya bercabang
menjadi lebih banyak subdirektori, seperti "/etc/init.d/
"
dan "/usr/local/
". Semua itu dilihat secara kolektif
disebut sebagai pohon direktori. Anda
dapat menganggap nama berkas absolut sebagai rute dari dasar pohon
("/
") ke akhir beberapa cabang (berkas). Anda juga
mendengar orang berbicara tentang pohon direktori seolah-olah itu adalah
pohon keluarga yang mencakup semua
keturunan langsung dari satu figur yang disebut direktori root
("/
"): jadi subdirektori memiliki induk, dan sebuah path menunjukkan keturunan
lengkap dari sebuah berkas. Ada juga jalur relatif yang dimulai di suatu
tempat selain direktori root. Anda harus ingat bahwa direktori
"../
" merujuk ke direktori induk. Terminologi ini juga
berlaku untuk direktori lain seperti struktur, seperti struktur data
hierarkis.
Tidak ada komponen nama path direktori khusus yang sesuai dengan perangkat
fisik, seperti hard disk Anda. Ini berbeda dari RT-11, CP/M, OpenVMS, MS-DOS, AmigaOS, dan Microsoft Windows, dengan path berisi nama
perangkat seperti "C:\
". (Namun, entri direktori memang
ada yang merujuk ke perangkat fisik sebagai bagian dari sistem berkas
normal. Lihat Bagian 1.2.2, “Sistem file internal”.)
![]() |
Catatan |
---|---|
Meskipun Anda dapat menggunakan hampir
semua huruf atau simbol dalam nama berkas, dalam praktiknya adalah ide yang
buruk untuk melakukannya. Sebaiknya hindari karakter yang sering memiliki
arti khusus pada baris perintah, termasuk spasi, tab, baris baru, dan
karakter khusus lainnya: |
![]() |
Catatan |
---|---|
Kata "root" dapat berarti "pengguna root" atau "direktori root". Konteks penggunaannya harus membuatnya jelas. |
![]() |
Catatan |
---|---|
Kata path digunakan tidak hanya untuk nama berkas lengkap seperti di atas tetapi juga untuk path pencarian perintah. Makna yang dimaksud biasanya jelas dari konteksnya. |
Praktik terbaik terperinci untuk hierarki berkas dijelaskan dalam Standar
Hierarki Sistem Berkas/Filesystem Hierarchy Standard
("/usr/share/doc/debian-policy/fhs/fhs-2.3.txt.gz
" dan
hier
(7)). Anda harus mengingat fakta-fakta berikut di
awal.
Tabel 1.3. Daftar penggunaan direktori kunci
direktori | penggunaan direktori |
---|---|
/ |
direktori root |
/etc/ |
sistem file konfigurasi yang luas |
/var/log/ |
file log sistem |
/home/ |
semua direktori rumah bagi semua pengguna tanpa hak istimewa |
Mengikuti tradisi Unix, sistem GNU/Linux
Debian menyediakan sistem berkas di mana
data fisik pada hard disk dan perangkat penyimpanan lainnya berada, dan
interaksi dengan perangkat keras seperti layar konsol dan konsol serial
jarak jauh diwakili secara terpadu di bawah "/dev/
".
Setiap berkas, direktori, pipa bernama (cara dua program dapat berbagi data), atau perangkat fisik pada sistem Debian GNU/Linux memiliki struktur data yang disebut inode yang menjelaskan atribut terkait seperti pengguna yang memilikinya (pemilik), grup yang diikutinya, waktu terakhir diakses, dll. Gagasan untuk mewakili hampir semua hal dalam sistem berkas adalah inovasi Unix, dan kernel Linux modern telah mengembangkan gagasan ini lebih jauh. Sekarang, bahkan informasi tentang proses yang berjalan di komputer dapat ditemukan di sistem berkas.
Representasi abstrak dan kesatuan entitas fisik dan proses internal ini sangat kuat karena ini memungkinkan kita untuk menggunakan perintah yang sama untuk jenis operasi yang sama pada banyak perangkat yang sama sekali berbeda. Bahkan dimungkinkan untuk mengubah cara kerja kernel dengan menulis data ke file khusus yang terkait dengan proses yang berjalan.
![]() |
Tip |
---|---|
Jika Anda perlu mengidentifikasi korespondensi antara pohon berkas dan
entitas fisik, jalankan |
Izin sistem berkas dari sistem seperti Unix ditentukan untuk tiga kategori pengguna yang terpengaruh.
pengguna yang memiliki berkas (u)
Pengguna lain di grup tempat berkas tersebut termasuk (g)
Semua pengguna lainnya (o) juga disebut sebagai "dunia" dan "semua orang"
Untuk file tersebut, setiap izin yang sesuai memungkinkan tindakan berikut.
Izin baca (r) memungkinkan pemilik untuk memeriksa konten berkas.
Izin tulis (w) memungkinkan pemilik untuk memodifikasi berkas.
Izin eksekusi (x) memungkinkan pemilik untuk menjalankan berkas sebagai perintah.
Untuk direktori, setiap izin yang sesuai memungkinkan tindakan berikut.
Izin baca (r) memungkinkan pemilik untuk membuat daftar isi direktori.
Izin tulis (w) memungkinkan pemilik untuk menambah atau menghapus berkas dalam direktori.
Izin eksekusi (x) memungkinkan pemilik untuk mengakses berkas dalam direktori.
Di sini, izin eksekusi pada direktori berarti tidak hanya mengizinkan pembacaan berkas di direktori itu tetapi juga untuk memungkinkan melihat atribut mereka, seperti ukuran dan waktu modifikasi.
ls
(1) digunakan untuk menampilkan informasi izin (dan
lebih banyak lagi) untuk berkas dan direktori. Ketika dipanggil dengan opsi
"-l
", ini menampilkan informasi berikut dalam urutan yang
diberikan.
Tipe berkas (karakter pertama)
Izin akses berkas (sembilan karakter, masing-masing terdiri dari tiga karakter untuk pengguna, grup, dan lainnya dalam urutan ini)
Banyaknya hard link ke berkas
Nama dari pengguna yang memiliki berkas tersebut
Nama dari grup pemilik berkas tersebut
Ukuran berkas dalam karakter (byte)
Tanggal dan waktu berkas (mtime)
Nama berkas
Tabel 1.4. Daftar karakter pertama dari keluaran "ls -l
"
karakter | arti |
---|---|
- |
berkas biasa |
d |
direktori |
l |
symlink |
c |
simpul perangkat karakter |
b |
simpul perangkat blok |
p |
pipa bernama |
s |
soket |
chown
(1) digunakan dari akun root untuk mengubah pemilik
berkas. chgrp
(1) digunakan dari pemilik berkas atau akun
root untuk mengubah grup berkas. chmod
(1) digunakan dari
pemilik berkas atau akun root untuk mengubah izin akses berkas dan
direktori. Sintaks dasar untuk memanipulasi berkas foo
adalah sebagai berikut.
# chown newowner foo # chgrp newgroup foo # chmod [ugoa][+-=][rwxXst][,...] foo
Misalnya, Anda dapat membuat pohon direktori agar dimiliki oleh pengguna
foo
dan dipakai bersama oleh grup bar
dengan cara berikut ini.
# cd /some/location/
# chown -R foo:bar .
# chmod -R ug+rwX,o=rX .
Ada tiga bit izin khusus lagi.
Bit set user ID (s atau S alih-alih x pengguna)
Bit set group ID (s atau S alih-alih x grup)
Bit sticky (t atau T alih-alih x lainnya)
Di sini keluaran dari "ls -l
" untuk bit ini adalah
dalam kapital jika bit eksekusi yang
disembunyikan oleh keluaran ini tak
ditata.
Menyetel set ID pengguna pada berkas executable memungkinkan pengguna untuk menjalankan berkas executable dengan ID pemilik berkas (misalnya root). Demikian pula, pengaturan set ID grup pada berkas executable memungkinkan pengguna untuk menjalankan berkas executable dengan ID grup berkas (misalnya root). Karena pengaturan ini dapat menyebabkan risiko keamanan, mengaktifkannya memerlukan kehati-hatian ekstra.
Mengatur set ID grup pada direktori akan mengaktifkan skema pembuatan berkas seperti BSD di mana semua berkas yang dibuat dalam direktori menjadi milik grup dari direktori.
Menyetel sticky bit pada direktori
mencegah berkas dalam direktori dihapus oleh pengguna yang bukan pemilik
berkas. Untuk mengamankan konten berkas di direktori yang dapat ditulis
dunia seperti "/tmp
" atau dalam direktori yang dapat
ditulis grup, seseorang tidak hanya harus mengatur ulang izin tulis untuk berkas tersebut, tetapi juga mengatur
sticky bit pada direktori. Jika tidak,
berkas dapat dihapus dan berkas baru dapat dibuat dengan nama yang sama oleh
setiap pengguna yang memiliki akses tulis ke direktori.
Berikut adalah beberapa contoh menarik dari izin berkas.
$ ls -l /etc/passwd /etc/shadow /dev/ppp /usr/sbin/exim4 crw------T 1 root root 108, 0 Oct 16 20:57 /dev/ppp -rw-r--r-- 1 root root 2761 Aug 30 10:38 /etc/passwd -rw-r----- 1 root shadow 1695 Aug 30 10:38 /etc/shadow -rwsr-xr-x 1 root root 973824 Sep 23 20:04 /usr/sbin/exim4 $ ls -ld /tmp /var/tmp /usr/local /var/mail /usr/src drwxrwxrwt 14 root root 20480 Oct 16 21:25 /tmp drwxrwsr-x 10 root staff 4096 Sep 29 22:50 /usr/local drwxr-xr-x 10 root root 4096 Oct 11 00:28 /usr/src drwxrwsr-x 2 root mail 4096 Oct 15 21:40 /var/mail drwxrwxrwt 3 root root 4096 Oct 16 21:20 /var/tmp
Ada mode numerik alternatif untuk menjelaskan izin berkas dengan
chmod
(1). Mode numerik ini menggunakan 3 hingga 4 digit
angka oktal lebar (radix = 8).
Tabel 1.5. Mode numerik untuk izin berkas dalam perintah chmod
(1)
nomor | arti |
---|---|
digit opsional pertama | jumlahdari set ID pengguna (=4), set ID grup (=2), dan sticky bit (=1) |
angka ke-2 | jumlah dari izin baca (=4), tulis (=2), dan eksekusi (=1) untuk pengguna |
angka ke-3 | begitu juga untuk grup |
angka ke-4 | begitu juga untuk lainnya |
Ini terdengar rumit tetapi sebenarnya cukup sederhana. Jika Anda melihat
beberapa (2-10) kolom pertama dari keluaran perintah "ls
-l
" dan membacanya sebagai representasi biner (basis=2) dari izin
berkas ("-" menjadi "0" dan "rwx" menjadi "1"), 3 digit terakhir dari nilai
mode numerik harus masuk akal sebagai representasi oktal (basis=8) dari izin
berkas bagi Anda.
Misalnya, coba yang berikut ini
$ touch foo bar $ chmod u=rw,go=r foo $ chmod 644 bar $ ls -l foo bar -rw-r--r-- 1 penguin penguin 0 Oct 16 21:39 bar -rw-r--r-- 1 penguin penguin 0 Oct 16 21:35 foo
![]() |
Tip |
---|---|
Jika Anda perlu mengakses informasi yang ditampilkan oleh " |
Izin apa yang diterapkan ke berkas atau direktori yang baru dibuat dibatasi
oleh perintah bawaan shell umask
. Lihat
dasbd
(1), bash
(1), dan
builtins
(7).
(file permissions) = (requested file permissions) & ~(umask value)
Tabel 1.6. Contoh-contoh nilai umask
umask | izin berkas dibuat | izin direktori dibuat | pengunaan |
---|---|---|---|
0022 |
-rw-r--r-- |
-rwxr-xr-x |
hanya dapat ditulis oleh pengguna |
0002 |
-rw-rw-r-- |
-rwxrwxr-x |
dapat ditulis oleh grup |
The Debian system uses a user private group (UPG) scheme as its default. A
UPG is created whenever a new user is added to the system. A UPG has the
same name as the user for which it was created and that user is the only
member of the UPG. UPG scheme makes it safe to set umask to
0002
since every user has their own private group. (In
some Unix variants, it is quite common to setup all normal users belonging
to a single users
group and is a good idea to set umask to 0022
for
security in such cases.)
![]() |
Tip |
---|---|
Aktifkan UPG dengan meletakkan " |
Untuk membuat izin grup diterapkan ke pengguna tertentu, pengguna tersebut
perlu dijadikan anggota grup menggunakan "sudo vigr
"
untuk /etc/group
dan "sudo vigr -s
"
untuk /etc/gshadow
. Anda harus log masuk setelah log
keluar (atau menjalankan "exec newgrp
") untuk
mengaktifkan konfigurasi grup baru.
![]() |
Catatan |
---|---|
Atau, Anda dapat secara dinamis menambahkan pengguna ke grup selama proses
otentikasi dengan menambahkan baris " |
Perangkat keras hanyalah jenis berkas lain di sistem Debian. Jika Anda memiliki masalah dalam mengakses perangkat seperti CD-ROM dan flash disk USB dari akun pengguna, Anda harus menjadikan pengguna tersebut anggota grup yang relevan.
Beberapa grup terkenal yang disediakan sistem mengizinkan anggotanya
mengakses berkas dan perangkat tertentu tanpa hak istimewa
root
.
Tabel 1.7. Daftar grup yang disediakan sistem terkenal untuk akses berkas
kelompok | deskripsi untuk berkas dan perangkat yang dapat diakses |
---|---|
dialout |
akses penuh dan langsung ke port serial
("/dev/ttyS[0-3] ") |
dip |
akses terbatas ke port serial untuk koneksi IP Dialup ke rekan tepercaya |
cdrom |
Drive CD-ROM, DVD+/-RW |
audio |
perangkat audio |
video |
perangkat video |
scanner |
pemindai |
adm |
log pemantauan sistem |
staff |
beberapa direktori untuk pekerjaan administratif junior:
"/usr/local ", "/home " |
![]() |
Tip |
---|---|
Anda harus tergabung dalam grup |
Beberapa grup terkenal yang disediakan sistem mengizinkan anggotanya untuk
menjalankan perintah tertentu tanpa hak istimewa root
.
Tabel 1.8. Daftar grup penting yang disediakan untuk eksekusi perintah tertentu
kelompok | perintah yang dapat diakses |
---|---|
sudo |
menjalankan sudo tanpa kata sandinya |
lpadmin |
menjalankan perintah untuk menambah, memodifikasi, dan menghapus printer dari database printer |
For the full listing of the system provided users and groups, see the recent
version of the "Users and Groups" document in
"/usr/share/doc/base-passwd/users-and-groups.html
"
provided by the base-passwd
package.
See passwd
(5), group
(5),
shadow
(5), newgrp
(1),
vipw
(8), vigr
(8), and
pam_group
(8) for management commands of the user and
group system.
There are three types of timestamps for a GNU/Linux file.
Tabel 1.9. List of types of timestamps
jenis | meaning (historic Unix definition) |
---|---|
mtime | the file modification time (ls -l ) |
ctime | waktu perubahan status berkas (ls -lc ) |
atime | waktu akses berkas terakhir (ls -lu ) |
![]() |
Catatan |
---|---|
ctime bukanlah waktu pembuatan berkas. |
![]() |
Catatan |
---|---|
The actual value of atime on GNU/Linux system may be different from that of the historic Unix definition. |
Overwriting a file changes all of the mtime, ctime, and atime attributes of the file.
Changing ownership or permission of a file changes the ctime and atime attributes of the file.
Reading a file changes the atime attribute of the file on the historic Unix system.
Reading a file changes the atime
attribute of the file on the GNU/Linux system if its filesystem is mounted
with "strictatime
".
Reading a file for the first time or after one day changes the atime attribute of the file on the GNU/Linux system
if its filesystem is mounted with "relatime
". (default
behavior since Linux 2.6.30)
Reading a file doesn't change the atime
attribute of the file on the GNU/Linux system if its filesystem is mounted
with "noatime
".
![]() |
Catatan |
---|---|
The " |
Use touch
(1) command to change timestamps of existing
files.
For timestamps, the ls
command outputs localized strings
under non-English locale ("fr_FR.UTF-8
").
$ LANG=C ls -l foo -rw-rw-r-- 1 penguin penguin 0 Oct 16 21:35 foo $ LANG=en_US.UTF-8 ls -l foo -rw-rw-r-- 1 penguin penguin 0 Oct 16 21:35 foo $ LANG=fr_FR.UTF-8 ls -l foo -rw-rw-r-- 1 penguin penguin 0 oct. 16 21:35 foo
![]() |
Tip |
---|---|
See Bagian 9.3.4, “Customized display of time and date” to customize
" |
There are two methods of associating a file "foo
" with a
different filename "bar
".
Duplicate name for an existing file
"ln foo bar
"
Special file that points to another file by name
"ln -s foo bar
"
See the following example for changes in link counts and the subtle
differences in the result of the rm
command.
$ umask 002 $ echo "Original Content" > foo $ ls -li foo 1449840 -rw-rw-r-- 1 penguin penguin 17 Oct 16 21:42 foo $ ln foo bar # hard link $ ln -s foo baz # symlink $ ls -li foo bar baz 1449840 -rw-rw-r-- 2 penguin penguin 17 Oct 16 21:42 bar 1450180 lrwxrwxrwx 1 penguin penguin 3 Oct 16 21:47 baz -> foo 1449840 -rw-rw-r-- 2 penguin penguin 17 Oct 16 21:42 foo $ rm foo $ echo "New Content" > foo $ ls -li foo bar baz 1449840 -rw-rw-r-- 1 penguin penguin 17 Oct 16 21:42 bar 1450180 lrwxrwxrwx 1 penguin penguin 3 Oct 16 21:47 baz -> foo 1450183 -rw-rw-r-- 1 penguin penguin 12 Oct 16 21:48 foo $ cat bar Original Content $ cat baz New Content
The hardlink can be made within the same filesystem and shares the same
inode number which the "-i
" option with
ls
(1) reveals.
The symlink always has nominal file access permissions of
"rwxrwxrwx
", as shown in the above example, with the
effective access permissions dictated by permissions of the file that it
points to.
![]() |
Perhatian |
---|---|
It is generally a good idea not to create complicated symbolic links or hardlinks at all unless you have a very good reason. It may cause nightmares where the logical combination of the symbolic links results in loops in the filesystem. |
![]() |
Catatan |
---|---|
It is generally preferable to use symbolic links rather than hardlinks unless you have a good reason for using a hardlink. |
The ".
" directory links to the directory that it appears
in, thus the link count of any new directory starts at 2. The
"..
" directory links to the parent directory, thus the
link count of the directory increases with the addition of new
subdirectories.
If you are just moving to Linux from Windows, it soon becomes clear how well-designed the filename linking of Unix is, compared with the nearest Windows equivalent of "shortcuts". Because it is implemented in the filesystem, applications can't see any difference between a linked file and the original. In the case of hardlinks, there really is no difference.
A named pipe is a file that acts like a pipe. You put something into the file, and it comes out the other end. Thus it's called a FIFO, or First-In-First-Out: the first thing you put in the pipe is the first thing to come out the other end.
If you write to a named pipe, the process which is writing to the pipe
doesn't terminate until the information being written is read from the
pipe. If you read from a named pipe, the reading process waits until there
is nothing to read before terminating. The size of the pipe is always zero
--- it does not store data, it just links two processes like the
functionality offered by the shell "|
" syntax. However,
since this pipe has a name, the two processes don't have to be on the same
command line or even be run by the same user. Pipes were a very influential
innovation of Unix.
Misalnya, coba yang berikut ini
$ cd; mkfifo mypipe $ echo "hello" >mypipe & # put into background [1] 8022 $ ls -l mypipe prw-rw-r-- 1 penguin penguin 0 Oct 16 21:49 mypipe $ cat mypipe hello [1]+ Done echo "hello" >mypipe $ ls mypipe mypipe $ rm mypipe
Sockets are used extensively by all the Internet communication, databases, and the operating system itself. It is similar to the named pipe (FIFO) and allows processes to exchange information even between different computers. For the socket, those processes do not need to be running at the same time nor to be running as the children of the same ancestor process. This is the endpoint for the inter process communication (IPC). The exchange of information may occur over the network between different hosts. The two most common ones are the Internet socket and the Unix domain socket.
![]() |
Tip |
---|---|
" |
Device files refer to physical or virtual
devices on your system, such as your hard disk, video card, screen, or
keyboard. An example of a virtual device is the console, represented by
"/dev/console
".
There are 2 types of device files.
Character device
Accessed one character at a time
1 character = 1 byte
E.g. keyboard device, serial port, …
Block device
accessed in larger units called blocks
1 block > 1 byte
E.g. hard disk, …
You can read and write device files, though the file may well contain binary
data which may be an incomprehensible-to-humans gibberish. Writing data
directly to these files is sometimes useful for the troubleshooting of
hardware connections. For example, you can dump a text file to the printer
device "/dev/lp0
" or send modem commands to the
appropriate serial port "/dev/ttyS0
". But, unless this
is done carefully, it may cause a major disaster. So be cautious.
![]() |
Catatan |
---|---|
For the normal access to a printer, use |
The device node number are displayed by executing ls
(1)
as the following.
$ ls -l /dev/sda /dev/sr0 /dev/ttyS0 /dev/zero brw-rw---T 1 root disk 8, 0 Oct 16 20:57 /dev/sda brw-rw---T+ 1 root cdrom 11, 0 Oct 16 21:53 /dev/sr0 crw-rw---T 1 root dialout 4, 64 Oct 16 20:57 /dev/ttyS0 crw-rw-rw- 1 root root 1, 5 Oct 16 20:57 /dev/zero
"/dev/sda
" has the major device number 8 and the minor
device number 0. This is read/write accessible by users belonging to the
disk
group.
"/dev/sr0
" has the major device number 11 and the minor
device number 0. This is read/write accessible by users belonging to the
cdrom
group.
"/dev/ttyS0
" has the major device number 4 and the minor
device number 64. This is read/write accessible by users belonging to the
dialout
group.
"/dev/zero
" has the major device number 1 and the minor
device number 5. This is read/write accessible by anyone.
On the modern Linux system, the filesystem under "/dev/
"
is automatically populated by the udev
(7) mechanism.
There are some special device files.
Tabel 1.10. List of special device files
device file | aksi | description of response |
---|---|---|
/dev/null |
read | return "end-of-file (EOF) character" |
/dev/null |
write | return nothing (a bottomless data dump pit) |
/dev/zero |
read | return "the \0 (NUL) character" (not the same as the
number zero ASCII) |
/dev/random |
read | return random characters from a true random number generator, delivering real entropy (slow) |
/dev/urandom |
read | return random characters from a cryptographically secure pseudorandom number generator |
/dev/full |
write | return the disk-full (ENOSPC) error |
These are frequently used in conjunction with the shell redirection (see Bagian 1.5.8, “Typical command sequences and shell redirection”).
The procfs and sysfs mounted on "/proc
" and
"/sys
" are the pseudo-filesystem and expose internal data
structures of the kernel to the userspace. In other word, these entries are
virtual, meaning that they act as a convenient window into the operation of
the operating system.
The directory "/proc
" contains (among other things) one
subdirectory for each process running on the system, which is named after
the process ID (PID). System utilities that access process information, such
as ps
(1), get their information from this directory
structure.
The directories under "/proc/sys/
" contain interfaces to
change certain kernel parameters at run time. (You may do the same through
the specialized sysctl
(8) command or its
preload/configuration file "/etc/sysctl.conf
".)
People frequently panic when they notice one file in particular -
"/proc/kcore
" - which is generally huge. This is (more
or less) a copy of the content of your computer's memory. It's used to
debug the kernel. It is a virtual file that points to computer memory, so
don't worry about its size.
The directory under "/sys
" contains exported kernel data
structures, their attributes, and their linkages between them. It also
contains interfaces to change certain kernel parameters at run time.
See "proc.txt(.gz)
", "sysfs.txt(.gz)
"
and other related documents in the Linux kernel documentation
("/usr/share/doc/linux-doc-*/Documentation/filesystems/*
")
provided by the linux-doc-*
package.
The tmpfs is a temporary filesystem which keeps all files in the virtual memory. The data of the tmpfs in the page cache on memory may be swapped out to the swap space on disk as needed.
The directory "/run
" is mounted as the tmpfs in the early
boot process. This enables writing to it even when the directory
"/
" is mounted as read-only. This is the new location
for the storage of transient state files and replaces several locations
described in the Filesystem
Hierarchy Standard version 2.3:
"/var/run
" → "/run
"
"/var/lock
" → "/run/lock
"
"/dev/shm
" → "/run/shm
"
See "tmpfs.txt(.gz)
" in the Linux kernel documentation
("/usr/share/doc/linux-doc-*/Documentation/filesystems/*
")
provided by the linux-doc-*
package.
Midnight Commander (MC) is a GNU "Swiss army knife" for the Linux console and other terminal environments. This gives newbie a menu driven console experience which is much easier to learn than standard Unix commands.
You may need to install the Midnight Commander package which is titled
"mc
" by the following.
$ sudo apt-get install mc
Use the mc
(1) command to explore the Debian system. This
is the best way to learn. Please explore few interesting locations just
using the cursor keys and Enter key.
"/etc
" and its subdirectories
"/var/log
" and its subdirectories
"/usr/share/doc
" and its subdirectories
"/sbin
" and "/bin
"
In order to make MC to change working directory upon exit and
cd
to the directory, I suggest to modify
"~/.bashrc
" to include a script provided by the
mc
package.
. /usr/lib/mc/mc.sh
See mc
(1) (under the "-P
" option) for
the reason. (If you do not understand what exactly I am talking here, you
can do this later.)
MC can be started by the following.
$ mc
MC takes care of all file operations through its menu, requiring minimal user effort. Just press F1 to get the help screen. You can play with MC just by pressing cursor-keys and function-keys.
![]() |
Catatan |
---|---|
In some consoles such as |
If you encounter character encoding problem which displays garbage
characters, adding "-a
" to MC's command line may help
prevent problems.
If this doesn't clear up your display problems with MC, see Bagian 9.5.6, “The terminal configuration”.
The default is two directory panels containing file lists. Another useful
mode is to set the right window to "information" to see file access
privilege information, etc. Following are some essential keystrokes. With
the gpm
(8) daemon running, one can use a mouse on Linux
character consoles, too. (Make sure to press the shift-key to obtain the
normal behavior of cut and paste in MC.)
Tabel 1.11. The key bindings of MC
key | key binding |
---|---|
F1 |
help menu |
F3 |
internal file viewer |
F4 |
internal editor |
F9 |
activate pull down menu |
F10 |
exit Midnight Commander |
Tab |
move between two windows |
Insert or Ctrl-T |
mark file for a multiple-file operation such as copy |
Del |
delete file (be careful---set MC to safe delete mode) |
Cursor keys | self-explanatory |
cd
command changes the directory shown on the selected
screen.
Ctrl-Enter
or Alt-Enter
copies a
filename to the command line. Use this with cp
(1) and
mv
(1) commands together with command-line editing.
Alt-Tab
shows shell filename expansion choices.
One can specify the starting directory for both windows as arguments to MC;
for example, "mc /etc /root
".
Esc
+ n-key
→ Fn
(i.e., Esc
+ 1
→
F1
, etc.; Esc
+ 0
→
F10
)
Pressing Esc
before the key has the same effect as
pressing the Alt
and the key together.; i.e., type
Esc
+ c
for Alt-C
.
Esc
is called meta-key and sometimes noted as
"M-
".
The internal editor has an interesting cut-and-paste scheme. Pressing
F3
marks the start of a selection, a second
F3
marks the end of selection and highlights the
selection. Then you can move your cursor. If you press F6, the selected
area is moved to the cursor location. If you press F5, the selected area is
copied and inserted at the cursor location. F2
saves the
file. F10
gets you out. Most cursor keys work
intuitively.
This editor can be directly started on a file using one of the following commands.
$ mc -e filename_to_edit
$ mcedit filename_to_edit
This is not a multi-window editor, but one can use multiple Linux consoles to achieve the same effect. To copy between windows, use Alt-Fn keys to switch virtual consoles and use "File→Insert file" or "File→Copy to file" to move a portion of a file to another file.
This internal editor can be replaced with any external editor of choice.
Also, many programs use the environment variables
"$EDITOR
" or "$VISUAL
" to decide which
editor to use. If you are uncomfortable with vim
(1) or
nano
(1) initially, you may set these to
"mcedit
" by adding the following lines to
"~/.bashrc
".
export EDITOR=mcedit export VISUAL=mcedit
I do recommend setting these to "vim
" if possible.
If you are uncomfortable with vim
(1), you can keep using
mcedit
(1) for most system maintenance tasks.
MC is a very smart viewer. This is a great tool for searching words in
documents. I always use this for files in the
"/usr/share/doc
" directory. This is the fastest way to
browse through masses of Linux information. This viewer can be directly
started using one of the following commands.
$ mc -v path/to/filename_to_view
$ mcview path/to/filename_to_view
Press Enter on a file, and the appropriate program handles the content of the file (see Bagian 9.4.11, “Customizing program to be started”). This is a very convenient MC feature.
Tabel 1.12. The reaction to the enter key in MC
file type | reaction to enter key |
---|---|
executable file | execute command |
man file | pipe content to viewer software |
html file | pipe content to web browser |
"*.tar.gz " and "*.deb " file |
browse its contents as if subdirectory |
In order to allow these viewer and virtual file features to function,
viewable files should not be set as executable. Change their status using
chmod
(1) or via the MC file menu.
MC can be used to access files over the Internet using FTP. Go to the menu
by pressing F9
, then type "p
" to
activate the FTP virtual filesystem. Enter a URL in the form
"username:passwd@hostname.domainname
", which retrieves a
remote directory that appears like a local one.
Try "[deb.debian.org/debian]" as the URL and browse the Debian archive.
Although MC enables you to do almost everything, it is very important for you to learn how to use the command line tools invoked from the shell prompt and become familiar with the Unix-like work environment.
You can select your login shell with chsh
(1).
Tabel 1.13. List of shell programs
paket | popcon | ukuran | POSIX shell | deskripsi |
---|---|---|---|---|
bash
|
V:796, I:999 | 6470 | Ya | Bash: the GNU Bourne Again SHell (de facto standard) |
bash-completion
|
V:31, I:922 | 1523 | N/A | programmable completion for the bash shell |
dash
|
V:913, I:993 | 221 | Ya | Debian Almquist Shell, good for shell script |
zsh
|
V:36, I:74 | 2467 | Ya | Z shell: the standard shell with many enhancements |
tcsh
|
V:8, I:28 | 1316 | Tidak | TENEX C Shell: an enhanced version of Berkeley csh |
mksh
|
V:7, I:12 | 1478 | Ya | A version of the Korn shell |
csh
|
V:2, I:8 | 343 | Tidak | OpenBSD C Shell, a version of Berkeley csh |
sash
|
V:0, I:6 | 1090 | Ya | Stand-alone shell with builtin
commands (Not meant for standard "/bin/sh ") |
ksh
|
V:2, I:15 | 3284 | Ya | the real, AT&T version of the Korn shell |
rc
|
V:0, I:1 | 169 | Tidak | implementation of the AT&T Plan 9 rc shell |
posh
|
V:0, I:0 | 190 | Ya | Policy-compliant Ordinary SHell (pdksh derivative) |
![]() |
Tip |
---|---|
Although POSIX-like shells share the basic syntax, they can differ in behavior for things as basic as shell variables and glob expansions. Please check their documentation for details. |
In this tutorial chapter, the interactive shell always means
bash
.
You can customize bash
(1) behavior by
"~/.bashrc
".
For example, try the following.
# enable bash-completion if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi # CD upon exiting MC . /usr/lib/mc/mc.sh # set CDPATH to a good one CDPATH=.:/usr/share/doc:~:~/Desktop:~ export CDPATH PATH="${PATH+$PATH:}/usr/sbin:/sbin" # set PATH so it includes user's private bin if it exists if [ -d ~/bin ] ; then PATH="~/bin${PATH+:$PATH}" fi export PATH EDITOR=vim export EDITOR
![]() |
Tip |
---|---|
You can find more |
![]() |
Tip |
---|---|
The |
In the Unix-like environment, there are few
key strokes which have special meanings. Please note that on a normal Linux
character console, only the left-hand Ctrl
and
Alt
keys work as expected. Here are few notable key
strokes to remember.
Tabel 1.14. List of key bindings for bash
key | description of key binding |
---|---|
Ctrl-U |
erase line before cursor |
Ctrl-H |
erase a character before cursor |
Ctrl-D |
terminate input (exit shell if you are using shell) |
Ctrl-C |
terminate a running program |
Ctrl-Z |
temporarily stop program by moving it to the background job |
Ctrl-S |
halt output to screen |
Ctrl-Q |
reactivate output to screen |
Ctrl-Alt-Del |
reboot/halt the system, see inittab (5) |
Left-Alt-key (optionally, Windows-key ) |
meta-key for Emacs and the similar UI |
Up-arrow |
start command history search under bash |
Ctrl-R |
start incremental command history search under bash |
Tab |
complete input of the filename to the command line under
bash |
Ctrl-V Tab |
input Tab without expansion to the command line under
bash |
![]() |
Tip |
---|---|
The terminal feature of |
Mouse operations for text on Debian system mix 2 styles with some twists:
Traditional Unix style mouse operations:
use 3 buttons (click)
use PRIMARY
used by X applications such as xterm
and text
applications in Linux console
Modern GUI style mouse operations:
use 2 buttons (drag + click)
use PRIMARY and CLIPBOARD
used in Modern GUI applications such as gnome-terminal
Tabel 1.15. List of mouse operations and related key actions on Debian
aksi | response |
---|---|
Left-click-and-drag mouse | select range as PRIMARY selection |
Left-click | select the start of range for PRIMARY selection |
Right-click (traditional) | select the end of range for PRIMARY selection |
Right-click (modern) | context dependent menu (cut/copy/paste) |
Middle-click or Shift-Ins |
insert PRIMARY selection at the cursor |
Ctrl-X |
cut PRIMARY selection to CLIPBOARD |
Ctrl-C (Shift-Ctrl-C in terminal) |
copy PRIMARY selection to CLIPBOARD |
Ctrl-V |
paste CLIPBOARD at the cursor |
Here, the PRIMARY selection is the highlighted text range. Within the
terminal program, Shift-Ctrl-C
is used instead to avoid
terminating a running program.
The center wheel on the modern wheel mouse is considered middle mouse button and can be used for middle-click. Clicking left and right mouse buttons together serves as the middle-click under the 2 button mouse system situation.
In order to use a mouse in Linux character consoles, you need to have
gpm
(8) running as daemon.
The less
(1) command is the enhanced pager (file content
browser). It reads the file specified by its command argument or its
standard input. Hit "h
" if you need help while browsing
with the less
command. It can do much more than
more
(1) and can be supercharged by executing
"eval $(lesspipe)
" or "eval
$(lessfile)
" in the shell startup script. See more in
"/usr/share/doc/less/LESSOPEN
". The
"-R
" option allows raw character output and enables ANSI
color escape sequences. See less
(1).
You should become proficient in one of variants of Vim or Emacs programs which are popular in the Unix-like system.
I think getting used to Vim commands is the right thing to do, since
Vi-editor is always there in the Linux/Unix world. (Actually, original
vi
or new nvi
are programs you find
everywhere. I chose Vim instead for newbie since it offers you help through
F1
key while it is similar enough and more powerful.)
If you chose either Emacs or XEmacs instead as your choice of the editor, that is another good choice indeed, particularly for programming. Emacs has a plethora of other features as well, including functioning as a newsreader, directory editor, mail program, etc. When used for programming or editing shell scripts, it intelligently recognizes the format of what you are working on, and tries to provide assistance. Some people maintain that the only program they need on Linux is Emacs. Ten minutes learning Emacs now can save hours later. Having the GNU Emacs manual for reference when learning Emacs is highly recommended.
All these programs usually come with tutoring program for you to learn them
by practice. Start Vim by typing "vim
" and press
F1-key. You should at least read the first 35 lines. Then do the online
training course by moving cursor to "|tutor|
" and
pressing Ctrl-]
.
![]() |
Catatan |
---|---|
Good editors, such as Vim and Emacs, can handle UTF-8 and other exotic encoding texts correctly. It is a good idea to use the GUI environment in the UTF-8 locale and to install required programs and fonts to it. Editors have options to set the file encoding independent of the GUI environment. Please refer to their documentation on multibyte text. |
Debian comes with a number of different editors. We recommend to install the
vim
package, as mentioned above.
Debian provides unified access to the system default editor via command
"/usr/bin/editor
" so other programs (e.g.,
reportbug
(1)) can invoke it. You can change it by the
following.
$ sudo update-alternatives --config editor
The choice "/usr/bin/vim.basic
" over
"/usr/bin/vim.tiny
" is my recommendation for newbies
since it supports syntax highlighting.
![]() |
Tip |
---|---|
Many programs use the environment variables " |
The recent vim
(1) starts itself in the sane
"nocompatible
" option and enters into the
NORMAL
mode.[1]
Tabel 1.16. List of basic Vim key strokes
mode | key strokes | aksi |
---|---|---|
NORMAL |
:help|only |
display the help file |
NORMAL |
:e filename.ext |
open new buffer to edit filename.ext |
NORMAL |
:w |
overwrite current buffer to the original file |
NORMAL |
:w filename.ext |
write current buffer to filename.ext |
NORMAL |
:q |
quit vim |
NORMAL |
:q! |
force to quit vim |
NORMAL |
:only |
close all other split open windows |
NORMAL |
:set nocompatible? |
check if vim is in the sane
nocompatible mode |
NORMAL |
:set nocompatible |
set vim to the sane nocompatible mode |
NORMAL |
i |
enter the INSERT mode |
NORMAL |
R |
enter the REPLACE mode |
NORMAL |
v |
enter the VISUAL mode |
NORMAL |
V |
enter the linewise VISUAL mode |
NORMAL |
Ctrl-V |
enter the blockwise VISUAL mode |
except TERMINAL-JOB |
ESC -key |
enter the NORMAL mode |
NORMAL |
:term |
enter the TERMINAL-JOB mode |
TERMINAL-NORMAL |
i |
enter the TERMINAL-JOB mode |
TERMINAL-JOB |
Ctrl-W N (or Ctrl-\
Ctrl-N ) |
enter the TERMINAL-NORMAL mode |
TERMINAL-JOB |
Ctrl-W : |
masuk mode Ex dalam mode
TERMINAL-NORMAL |
Harap gunakan program "vimtutor
" untuk belajar
vim
melalui suatu kursus tutorial interaktif.
The vim
program changes its behavior to typed key strokes
based on mode. Typing in key strokes to
the buffer is mostly done in INSERT
-mode and
REPLACE
-mode. Moving cursor is mostly done in
NORMAL
-mode. Interactive selection is done in
VISUAL
-mode. Typing ":
" in
NORMAL
-mode changes its mode to
Ex
-mode. Ex
-mode accepts commands.
![]() |
Tip |
---|---|
The Vim comes with the Netrw package.
Netrw supports reading files, writing files, browsing directories over a
network, and local browsing! Try Netrw with " |
For the advanced configuration of vim
, see Bagian 9.2, “Customizing vim”.
The output of the shell command may roll off your screen and may be lost forever. It is a good practice to log shell activities into the file for you to review them later. This kind of record is essential when you perform any system administration tasks.
![]() |
Tip |
---|---|
The new Vim (version>=8.2) can be used to record the shell activities
cleanly using |
The basic method of recording the shell activity is to run it under
script
(1).
Misalnya, coba yang berikut ini
$ script Script started, file is typescript
Do whatever shell commands under script
.
Press Ctrl-D
to exit script
.
$ vim typescript
See Bagian 9.1.1, “Recording the shell activities cleanly” .
Let's learn basic Unix commands. Here I use "Unix" in its generic sense.
Any Unix clone OSs usually offer equivalent commands. The Debian system is
no exception. Do not worry if some commands do not work as you wish now. If
alias
is used in the shell, its corresponding command
outputs are different. These examples are not meant to be executed in this
order.
Try all following commands from the non-privileged user account.
Tabel 1.17. List of basic Unix commands
command | deskripsi |
---|---|
pwd |
display name of current/working directory |
whoami |
display current user name |
id |
display current user identity (name, uid, gid, and associated groups) |
file foo |
display a type of file for the file
"foo " |
type -p namaperintah |
display a file location of command
"commandname " |
which namaperintah |
, , |
type namaperintah |
display information on command
"commandname " |
apropos kata-kunci |
find commands related to "key-word " |
man -k kata-kunci |
, , |
whatis namaperintah |
display one line explanation on command
"commandname " |
man -a namaperintah |
display explanation on command
"commandname " (Unix style) |
info namaperintah |
display rather long explanation on command
"commandname " (GNU style) |
ls |
list contents of directory (non-dot files and directories) |
ls -a |
list contents of directory (all files and directories) |
ls -A |
list contents of directory (almost all files and directories, i.e., skip
".. " and ". ") |
ls -la |
list all contents of directory with detail information |
ls -lai |
list all contents of directory with inode number and detail information |
ls -d |
list all directories under the current directory |
tree |
display file tree contents |
lsof foo |
list open status of file "foo " |
lsof -p pid |
list files opened by the process ID:
"pid " |
mkdir foo |
make a new directory "foo " in the
current directory |
rmdir foo |
remove a directory "foo " in the
current directory |
cd foo |
change directory to the directory
"foo " in the current directory or in
the directory listed in the variable "$CDPATH " |
cd / |
change directory to the root directory |
cd |
change directory to the current user's home directory |
cd /foo |
change directory to the absolute path directory
"/foo " |
cd .. |
change directory to the parent directory |
cd ~foo |
change directory to the home directory of the user
"foo " |
cd - |
change directory to the previous directory |
</etc/motd pager |
display contents of "/etc/motd " using the default pager |
touch junkfile |
create a empty file "junkfile " |
cp foo bar |
copy a existing file "foo " to a new
file "bar " |
rm junkfile |
remove a file "junkfile " |
mv foo bar |
rename an existing file "foo " to a
new name "bar "
("bar " must not exist) |
mv foo bar |
move an existing file "foo " to a new
location
"bar/foo " (the
directory "bar " must exist) |
mv foo
bar/baz |
move an existing file "foo " to a new
location with a new name
"bar/baz " (the
directory "bar " must exist but the
directory
"bar/baz " must
not exist) |
chmod 600 foo |
make an existing file "foo " to be
non-readable and non-writable by the other people (non-executable for all) |
chmod 644 foo |
make an existing file "foo " to be
readable but non-writable by the other people (non-executable for all) |
chmod 755 foo |
make an existing file "foo " to be
readable but non-writable by the other people (executable for all) |
find . -name pattern |
find matching filenames using shell
"pattern " (slower) |
locate -d . pattern |
find matching filenames using shell
"pattern " (quicker using regularly
generated database) |
grep -e "pattern" *.html |
find a "pattern " in all files ending
with ".html " in current directory and display them all |
top |
display process information using full screen, type "q "
to quit |
ps aux | pager |
display information on all the running processes using BSD style output |
ps -ef | pager |
display information on all the running processes using Unix system-V style output |
ps aux | grep -e "[e]xim4*" |
display all processes running "exim " and
"exim4 " |
ps axf | pager |
display information on all the running processes with ASCII art output |
kill 1234 |
kill a process identified by the process ID: "1234" |
gzip foo |
compress "foo " to create
"foo.gz " using the Lempel-Ziv coding
(LZ77) |
gunzip foo.gz |
decompress "foo.gz " to create
"foo " |
bzip2 foo |
compress "foo " to create
"foo.bz2 " using the Burrows-Wheeler
block sorting text compression algorithm, and Huffman coding (better
compression than gzip ) |
bunzip2 foo.bz2 |
decompress "foo.bz2 " to create
"foo " |
xz foo |
compress "foo " to create
"foo.xz " using the Lempel–Ziv–Markov
chain algorithm (better compression than bzip2 ) |
unxz foo.xz |
decompress "foo.xz " to create
"foo " |
tar -xvf foo.tar |
extract files from "foo.tar " archive |
tar -xvzf foo.tar.gz |
extract files from gzipped
"foo.tar.gz " archive |
tar -xvjf foo.tar.bz2 |
extract files from "foo.tar.bz2 "
archive |
tar -xvJf foo.tar.xz |
extract files from "foo.tar.xz "
archive |
tar -cvf foo.tar
bar/ |
archive contents of folder "bar/ " in
"foo.tar " archive |
tar -cvzf foo.tar.gz
bar/ |
archive contents of folder "bar/ " in
compressed "foo.tar.gz " archive |
tar -cvjf foo.tar.bz2
bar/ |
archive contents of folder "bar/ " in
"foo.tar.bz2 " archive |
tar -cvJf foo.tar.xz
bar/ |
archive contents of folder "bar/ " in
"foo.tar.xz " archive |
zcat README.gz | pager |
display contents of compressed "README.gz " using the
default pager |
zcat README.gz > foo |
create a file "foo " with the decompressed content of
"README.gz " |
zcat README.gz >> foo |
append the decompressed content of "README.gz " to the end
of the file "foo " (if it does not exist, create it first) |
![]() |
Catatan |
---|---|
Unix has a tradition to hide filenames which start with
" For The default pager of the bare bone Debian system is
The " |
Please traverse directories and peek into the system using the above commands as training. If you have questions on any of console commands, please make sure to read the manual page.
Misalnya, coba yang berikut ini
$ man man $ man bash $ man builtins $ man grep $ man ls
The style of man pages may be a little hard to get used to, because they are rather terse, particularly the older, very traditional ones. But once you get used to it, you come to appreciate their succinctness.
Please note that many Unix-like commands including ones from GNU and BSD display brief help information if you invoke them in one of the following ways (or without any arguments in some cases).
$ commandname --help $ commandname -h
Now you have some feel on how to use the Debian system. Let's look deep
into the mechanism of the command execution in the Debian system. Here, I
have simplified reality for the newbie. See bash
(1) for
the exact explanation.
A simple command is a sequence of components.
Variable assignments (optional)
Command name
Arguments (optional)
Redirections (optional: >
,
>>
, <
,
<<
, etc.)
Control operator (optional: &&
,
||
, newline , ;
, &
, (
, )
)
The values of some environment variables change the behavior of some Unix commands.
Default values of environment variables are initially set by the PAM system and then some of them may be reset by some application programs.
The PAM system such as pam_env
may set environment
variables by /etc/pam.conf
",
"/etc/environment
" and
"/etc/default/locale
".
The display manager such as gdm3
may reset environment
variables for GUI session.
The user specific program initialization may reset environment variables by
"~/.profile
", "~/.bash_profile
" and
"~/.bashrc
".
The default locale is defined in the "$LANG
" environment
variable and is configured as "LANG=xx_YY.UTF-8
" by the
installer or by the subsequent GUI configuration, e.g., "Settings" → "Region
& Language" → "Language" / "Formats" for GNOME.
![]() |
Catatan |
---|---|
I recommend you to configure the system environment just by the
" |
The full locale value given to "$LANG
" variable consists
of 3 parts: "xx_YY.ZZZZ
".
Tabel 1.19. List of locale recommendations
locale recommendation | Language (area) |
---|---|
en_US.UTF-8 |
English (USA) |
en_GB.UTF-8 |
English (Great Britain) |
fr_FR.UTF-8 |
French (France) |
de_DE.UTF-8 |
German (Germany) |
it_IT.UTF-8 |
Italian (Italy) |
es_ES.UTF-8 |
Spanish (Spain) |
ca_ES.UTF-8 |
Catalan (Spain) |
sv_SE.UTF-8 |
Swedish (Sweden) |
pt_BR.UTF-8 |
Portuguese (Brazil) |
ru_RU.UTF-8 |
Russian (Russia) |
zh_CN.UTF-8 |
Chinese (P.R. of China) |
zh_TW.UTF-8 |
Chinese (Taiwan R.O.C.) |
ja_JP.UTF-8 |
Japanese (Japan) |
ko_KR.UTF-8 |
Korean (Republic of Korea) |
vi_VN.UTF-8 |
Vietnamese (Vietnam) |
Typical command execution uses a shell line sequence as the following.
$ echo $LANG en_US.UTF-8 $ date -u Wed 19 May 2021 03:18:43 PM UTC $ LANG=fr_FR.UTF-8 date -u mer. 19 mai 2021 15:19:02 UTC
Here, the program date
(1) is executed with different
locale values.
Most command executions usually do not have preceding environment variable definition. For the above example, you can alternatively execute as the following.
$ LANG=fr_FR.UTF-8 $ date -u mer. 19 mai 2021 15:19:24 UTC
![]() |
Tip |
---|---|
When filing a bug report, running and checking the command under
" |
For fine details of the locale configuration, see Bagian 8.1, “The locale”.
When you type a command into the shell, the shell searches the command in
the list of directories contained in the "$PATH
"
environment variable. The value of the "$PATH
"
environment variable is also called the shell's search path.
In the default Debian installation, the "$PATH
"
environment variable of user accounts may not include
"/sbin
" and "/usr/sbin
". For example,
the ifconfig
command needs to be issued with full path as
"/sbin/ifconfig
". (Similar ip
command
is located in "/bin
".)
You can change the "$PATH
" environment variable of Bash
shell by "~/.bash_profile
" or
"~/.bashrc
" files.
Many commands stores user specific configuration in the home directory and
changes their behavior by their contents. The home directory is identified
by the environment variable "$HOME
".
Tabel 1.20. List of "$HOME
" values
value of "$HOME " |
program execution situation |
---|---|
/ |
program run by the init process (daemon) |
/root |
program run from the normal root shell |
/home/normal_user |
program run from the normal user shell |
/home/normal_user |
program run from the normal user GUI desktop menu |
/home/normal_user |
program run as root with "sudo program " |
/root |
program run as root with "sudo -H program " |
![]() |
Tip |
---|---|
Shell expands " |
Some commands take arguments. Arguments starting with
"-
" or "--
" are called options and
control the behavior of the command.
$ date Thu 20 May 2021 01:08:08 AM JST $ date -R Thu, 20 May 2021 01:08:12 +0900
Here the command-line argument "-R
" changes
date
(1) behavior to output RFC2822 compliant date string.
Often you want a command to work with a group of files without typing all of them. The filename expansion pattern using the shell glob, (sometimes referred as wildcards), facilitate this need.
Tabel 1.21. Shell glob patterns
shell glob pattern | description of match rule |
---|---|
* |
filename (segment) not started with ". " |
.* |
filename (segment) started with ". " |
? |
exactly one character |
[…] |
exactly one character with any character enclosed in brackets |
[a-z] |
exactly one character with any character between "a " and
"z " |
[^…] |
exactly one character other than any character enclosed in brackets
(excluding "^ ") |
Misalnya, coba yang berikut ini
$ mkdir junk; cd junk; touch 1.txt 2.txt 3.c 4.h .5.txt ..6.txt $ echo *.txt 1.txt 2.txt $ echo * 1.txt 2.txt 3.c 4.h $ echo *.[hc] 3.c 4.h $ echo .* . .. .5.txt ..6.txt $ echo .*[^.]* .5.txt ..6.txt $ echo [^1-3]* 4.h $ cd ..; rm -rf junk
See glob
(7).
![]() |
Catatan |
---|---|
Unlike normal filename expansion by the shell, the shell pattern
" |
![]() |
Catatan |
---|---|
BASH can be tweaked to change its glob behavior with its shopt builtin
options such as " |
Each command returns its exit status (variable: "$?
") as
the return value.
Tabel 1.22. Command exit codes
command exit status | numeric return value | logical return value |
---|---|---|
sukses | zero, 0 | TRUE |
error | non-zero, -1 | FALSE |
For example, try the following.
$ [ 1 = 1 ] ; echo $? 0 $ [ 1 = 2 ] ; echo $? 1
![]() |
Catatan |
---|---|
Please note that, in the logical context for the shell, success is treated as the logical TRUE which has 0 (zero) as its value. This is somewhat non-intuitive and needs to be reminded here. |
Let's try to remember following shell command idioms typed in one line as a part of shell command.
Tabel 1.23. Shell command idioms
command idiom | deskripsi |
---|---|
command & |
background execution of
command in the subshell |
command1 | command2 |
pipe the standard output of
command1 to the standard input of
command2 (concurrent
execution) |
command1 2>&1 | command2 |
pipe both standard output and standard
error of command1 to the standard input of
command2 (concurrent
execution) |
command1 ; command2 |
execute command1 and command2
sequentially |
command1 && command2 |
execute command1 ; if successful, execute
command2 sequentially
(return success if both command1 and command2 are successful) |
command1 || command2 |
execute command1 ; if not successful, execute
command2 sequentially
(return success if command1 or command2 are successful) |
command > foo |
redirect standard output of command to a file
foo (overwrite) |
command 2> foo |
redirect standard error of command to a file
foo (overwrite) |
command >> foo |
redirect standard output of command to a file
foo (append) |
command 2>> foo |
redirect standard error of command to a file
foo (append) |
command > foo 2>&1 |
redirect both standard output and standard error of
command to a file foo |
command < foo |
redirect standard input of command to a file
foo |
command << delimiter |
redirect standard input of command to the following lines
until "delimiter " is met (here document) |
command <<- delimiter |
redirect standard input of command to the following lines
until "delimiter " is met (here document, the leading tab
characters are stripped from input lines) |
The Debian system is a multi-tasking system. Background jobs allow users to
run multiple programs in a single shell. The management of the background
process involves the shell builtins: jobs
,
fg
, bg
, and kill
.
Please read sections of bash(1) under "SIGNALS", and "JOB CONTROL", and
builtins
(1).
Misalnya, coba yang berikut ini
$ </etc/motd pager
$ pager </etc/motd
$ pager /etc/motd
$ cat /etc/motd | pager
Although all 4 examples of shell redirections display the same thing, the
last example runs an extra cat
command and wastes
resources with no reason.
The shell allows you to open files using the exec
builtin
with an arbitrary file descriptor.
$ echo Hello >foo
$ exec 3foo 4bar # open files
$ cat <&3 >&4 # redirect stdin to 3, stdout to 4
$ exec 3<&- 4>&- # close files
$ cat bar
Hello
The file descriptor 0-2 are predefined.
Tabel 1.24. Predefined file descriptors
perangkat | deskripsi | file descriptor |
---|---|---|
stdin |
standard input | 0 |
stdout |
standard output | 1 |
stderr |
standard error | 2 |
You can set an alias for the frequently used command.
Misalnya, coba yang berikut ini
$ alias la='ls -la'
Now, "la
" works as a short hand for "ls
-la
" which lists all files in the long listing format.
You can list any existing aliases by alias
(see
bash
(1) under "SHELL BUILTIN COMMANDS").
$ alias ... alias la='ls -la'
You can identity exact path or identity of the command by
type
(see bash
(1) under "SHELL BUILTIN
COMMANDS").
Misalnya, coba yang berikut ini
$ type ls ls is hashed (/bin/ls) $ type la la is aliased to ls -la $ type echo echo is a shell builtin $ type file file is /usr/bin/file
Here ls
was recently searched while
"file
" was not, thus "ls
" is "hashed",
i.e., the shell has an internal record for the quick access to the location
of the "ls
" command.
![]() |
Tip |
---|---|
In Unix-like work environment, text processing is done by piping text through chains of standard text processing tools. This was another crucial Unix innovation.
There are few standard text processing tools which are used very often on the Unix-like system.
No regular expression is used:
cat
(1) concatenates files and outputs the whole content.
tac
(1) concatenates files and outputs in reverse.
cut
(1) selects parts of lines and outputs.
head
(1) outputs the first part of files.
tail
(1) outputs the last part of files.
sort
(1) sorts lines of text files.
uniq
(1) removes duplicate lines from a sorted file.
tr
(1) translates or deletes characters.
diff
(1) compares files line by line.
Ekspresi reguler dasar (BRE) dipakai sebagai baku:
ed
(1) is a primitive line editor.
sed
(1) is a stream editor.
grep
(1) matches text with patterns.
vim
(1) is a screen editor.
emacs
(1) is a screen editor. (somewhat extended BRE)
Extended regular expression (ERE) is used:
awk
(1) does simple text processing.
egrep
(1) matches text with patterns.
tcl
(3tcl) can do every conceivable text processing: See
re_syntax
(3). Often used with tk
(3tk).
perl
(1) can do every conceivable text processing. See
perlre
(1).
pcregrep
(1) from the pcregrep
package
matches text with Perl
Compatible Regular Expressions (PCRE) pattern.
python
(1) with the re
module can do
every conceivable text processing. See
"/usr/share/doc/python/html/index.html
".
If you are not sure what exactly these commands do, please use "man
command
" to figure it out by yourself.
![]() |
Catatan |
---|---|
Sort order and range expression are locale dependent. If you wish to obtain traditional behavior for a command, use C locale or C.UTF-8 locale instead of normal UTF-8 ones (see Bagian 8.1, “The locale”). |
![]() |
Catatan |
---|---|
Perl regular expressions
( |
Regular expressions are used in many text processing tools. They are analogous to the shell globs, but they are more complicated and powerful.
The regular expression describes the matching pattern and is made up of text characters and metacharacters.
A metacharacter is just a character with a special meaning. There are 2 major styles, BRE and ERE, depending on the text tools as described above.
Tabel 1.25. Metacharacters for BRE and ERE
BRE | ERE | description of the regular expression |
---|---|---|
\ . [ ] ^ $ * |
\ . [ ] ^ $ * |
common metacharacters |
\+ \? \( \) \{ \} \| |
BRE only "\ " escaped metacharacters |
|
+ ? ( ) { } | |
ERE only non-"\ " escaped metacharacters |
|
c |
c |
match non-metacharacter
"c " |
\c |
\c |
match a literal character "c " even if
"c " is metacharacter
by itself |
. |
. |
match any character including newline |
^ |
^ |
position at the beginning of a string |
$ |
$ |
position at the end of a string |
\< |
\< |
position at the beginning of a word |
\> |
\> |
position at the end of a word |
[abc…] |
[abc…] |
match any characters in "abc… " |
[^abc…] |
[^abc…] |
match any characters except in "abc… " |
r* |
r* |
match zero or more regular expressions identified by "r " |
r\+ |
r+ |
match one or more regular expressions identified by "r " |
r\? |
r? |
match zero or one regular expressions identified by "r " |
r1\|r2 |
r1|r2 |
match one of the regular expressions identified by "r1 "
or "r2 " |
\(r1\|r2\) |
(r1|r2) |
match one of the regular expressions identified by "r1 "
or "r2 " and treat it as a bracketed regular expression |
The regular expression of emacs
is basically BRE but has been extended to treat
"+
"and "?
" as the metacharacters as in ERE. Thus, there are no needs to escape them with
"\
" in the regular expression of
emacs
.
grep
(1) can be used to perform the text search using the
regular expression.
Misalnya, coba yang berikut ini
$ egrep 'GNU.*LICENSE|Yoyodyne' /usr/share/common-licenses/GPL GNU GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE Yoyodyne, Inc., hereby disclaims all copyright interest in the program
![]() |
Tip |
---|---|
For the replacement expression, some characters have special meanings.
Tabel 1.26. The replacement expression
replacement expression | description of the text to replace the replacement expression |
---|---|
& |
what the regular expression matched (use \& in
emacs ) |
\n |
what the n-th bracketed regular expression matched ("n" being number) |
For Perl replacement string, "$&" is used instead of "&" and "$n" is used instead of "\n".
Misalnya, coba yang berikut ini
$ echo zzz1abc2efg3hij4 | \ sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/=&=/' zzz=1abc2efg3hij4= $ echo zzz1abc2efg3hij4 | \ sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/\2===\1/' zzzefg3hij4===1abc $ echo zzz1abc2efg3hij4 | \ perl -pe 's/(1[a-z]*)[0-9]*(.*)$/$2===$1/' zzzefg3hij4===1abc $ echo zzz1abc2efg3hij4 | \ perl -pe 's/(1[a-z]*)[0-9]*(.*)$/=$&=/' zzz=1abc2efg3hij4=
Here please pay extra attention to the style of the bracketed regular expression and how the matched strings are used in the text replacement process on different tools.
These regular expressions can be used for cursor movements and text replacement actions in some editors too.
The back slash "\
" at the end of line in the shell
commandline escapes newline as a white space character and continues shell
command line input to the next line.
Please read all the related manual pages to learn these commands.
The ed
(1) command can replace all instances of
"FROM_REGEX
" with "TO_TEXT
" in
"file
".
$ ed file <<EOF ,s/FROM_REGEX/TO_TEXT/g w q EOF
The sed
(1) command can replace all instances of
"FROM_REGEX
" with "TO_TEXT
" in
"file
".
$ sed -i -e 's/FROM_REGEX/TO_TEXT/g' file
The vim
(1) command can replace all instances of
"FROM_REGEX
" with "TO_TEXT
" in
"file
" by using ex
(1) commands.
$ vim '+%s/FROM_REGEX/TO_TEXT/gc' '+w' '+q' file
![]() |
Tip |
---|---|
The " |
Multiple files ("file1
", "file2
", and
"file3
") can be processed with regular expressions
similarly with vim
(1) or perl
(1).
$ vim '+argdo %s/FROM_REGEX/TO_TEXT/ge|update' '+q' file1 file2 file3
![]() |
Tip |
---|---|
The " |
$ perl -i -p -e 's/FROM_REGEX/TO_TEXT/g;' file1 file2 file3
In the perl(1) example, "-i
" is for the in-place editing
of each target file, and "-p
" is for the implicit loop
over all given files.
![]() |
Tip |
---|---|
Use of argument " |
![]() |
Catatan |
---|---|
|
Let's consider a text file called "DPL
" in which some
pre-2004 Debian project leader's names and their initiation date are listed
in a space-separated format.
Ian Murdock August 1993 Bruce Perens April 1996 Ian Jackson January 1998 Wichert Akkerman January 1999 Ben Collins April 2001 Bdale Garbee April 2002 Martin Michlmayr March 2003
![]() |
Tip |
---|---|
See "A Brief History of Debian" for the latest Debian leadership history. |
Awk is frequently used to extract data from these types of files.
Misalnya, coba yang berikut ini
$ awk '{ print $3 }' <DPL # month started August April January January April April March $ awk '($1=="Ian") { print }' <DPL # DPL called Ian Ian Murdock August 1993 Ian Jackson January 1998 $ awk '($2=="Perens") { print $3,$4 }' <DPL # When Perens started April 1996
Shells such as Bash can be also used to parse this kind of file.
Misalnya, coba yang berikut ini
$ while read first last month year; do echo $month done <DPL ... same output as the first Awk example
Here, the read
builtin command uses characters in
"$IFS
" (internal field separators) to split lines into
words.
If you change "$IFS
" to ":
", you can
parse "/etc/passwd
" with shell nicely.
$ oldIFS="$IFS" # save old value $ IFS=':' $ while read user password uid gid rest_of_line; do if [ "$user" = "bozo" ]; then echo "$user's ID is $uid" fi done < /etc/passwd bozo's ID is 1000 $ IFS="$oldIFS" # restore old value
(If Awk is used to do the equivalent, use "FS=':'
" to set
the field separator.)
IFS is also used by the shell to split results of parameter expansion, command substitution, and arithmetic expansion. These do not occur within double or single quoted words. The default value of IFS is space, tab, and newline combined.
Be careful about using this shell IFS tricks. Strange things may happen, when shell interprets some parts of the script as its input.
$ IFS=":," # use ":" and "," as IFS $ echo IFS=$IFS, IFS="$IFS" # echo is a Bash builtin IFS= , IFS=:, $ date -R # just a command output Sat, 23 Aug 2003 08:30:15 +0200 $ echo $(date -R) # sub shell --> input to main shell Sat 23 Aug 2003 08 30 36 +0200 $ unset IFS # reset IFS to the default $ echo $(date -R) Sat, 23 Aug 2003 08:30:50 +0200
The following scripts do nice things as a part of a pipe.
Tabel 1.27. List of script snippets for piping commands
script snippet (type in one line) | effect of command |
---|---|
find /usr -print |
find all files under "/usr " |
seq 1 100 |
print 1 to 100 |
| xargs -n 1 command |
run command repeatedly with each item from pipe as its argument |
| xargs -n 1 echo |
split white-space-separated items from pipe into lines |
| xargs echo |
merge all lines from pipe into a line |
| grep -e regex_pattern |
extract lines from pipe containing regex_pattern |
| grep -v -e regex_pattern |
extract lines from pipe not containing regex_pattern |
| cut -d: -f3 - |
extract third field from pipe separated by ": " (passwd
file etc.) |
| awk '{ print $3 }' |
extract third field from pipe separated by whitespaces |
| awk -F'\t' '{ print $3 }' |
extract third field from pipe separated by tab |
| col -bx |
remove backspace and expand tabs to spaces |
| expand - |
expand tabs |
| sort| uniq |
sort and remove duplicates |
| tr 'A-Z' 'a-z' |
convert uppercase to lowercase |
| tr -d '\n' |
concatenate lines into one line |
| tr -d '\r' |
remove CR |
| sed 's/^/# /' |
add "# " to the start of each line |
| sed 's/\.ext//g' |
remove ".ext " |
| sed -n -e 2p |
print the second line |
| head -n 2 - |
print the first 2 lines |
| tail -n 2 - |
print the last 2 lines |
A one-line shell script can loop over many files using
find
(1) and xargs
(1) to perform quite
complicated tasks. See Bagian 10.1.5, “Idioms for the selection of files”
and Bagian 9.4.9, “Repeating a command looping over files”.
When using the shell interactive mode becomes too complicated, please consider to write a shell script (see Bagian 12.1, “The shell script”).
[1] Even the older vim
can starts in the sane
"nocompatible
" mode by starting it with the
"-N
" option.