Showing posts with label Bash. Show all posts
Showing posts with label Bash. Show all posts

Saturday, June 22, 2024

Memahami Bash Return Value

Bash, salah satu Unix Shell yang paling banyak digunakan, merupakan salah satu (bahasa) pemrograman yang saya pakai selain Python. Fungsi Bash layaknya lem perekat, melekatkan program yang satu dengan yang lain, Python dengan C, Python dengan C++, dan yang paling sering, Python dengan Sistem Unix (Linux Kernel, OS, dl). Simpelnya, saya menulis program utama dengan Python dan memanggilnya dengan Bash. 

Ada salah satu konsep yang selama ini belum sepenuhnya saya pahami: return value. Kalau dalam Python return value sangat jelas, nilai yang dikembalikan dari fungsi tersebut. Dalam bash, maka nilai return value hanya ada dua: sukses atau gagal. Nilai return value tersebut bisa banyak, dari 0 sampai 255. Nilai 0 untuk sukses (perintah yang dieksekusi), nilai selainnya untuk gagal.

Kode bash di bawah ini mendemonstrasikan return value dalam bash. Tugasnya adalah mendeteksi nilai yang diberikan, saya masukkan dari 5 sampai 15. Jika nilainya lebih dari 10 maka sukses, jika kurang atau sama dengan 10 maka gagal ("failure").

#!/bin/bash
# bash_return_value_demo.sh

# set counter
failure_count=0
success_count=0

# Zero (0) return value as sign of success
success_function() {
    if [ $1 -gt 10 ]; then # greater than
        echo "Success!"
        success_count=$((success_count+1))
        return 0
    fi
}

# Non-zero (1-255) return value as sign of failure
failure_function() {
    if [ $1 -le 10 ]; then # less equal
        echo "Failure!"
        failure_count=$((failure_count+1))
        return 1
    fi
}

# loop from 5 to 15
for x in {5..15}; do
    # print the value of x
    echo "Value of x: $x"
    success_function $x 	# input x to success_function
    failure_function $x 	# input x to failure_function

    # Print the last return values via $?
    echo "Return value: $?"

done
# count the number of successful and failed commands
echo "Number of successful commands: $success_count"
echo "Number of failed commands: $failure_count"
Kode di atas sebenarnya self explanatory, bisa jelas sendiri per baris plus komentar di atas/sampingnya. Sederhananya, kita set counter di baris 7-8. Kemudian kita buat fungsi sukses dan gagal di baris 8 dan 17. Argument untuk fungsi di Bash di masukkan dalam fungsi yakni lewat $1 (untuk argumen pertama, $2 untuk argumen kedua dst). Kemudian buat loop untuk X mulai dari 5 sampai 15 (5..15), batas atas, 15, diproses juga, tidak seperti dalam bahasa Python. Di akhir skrip kita tampilkan jumlah perintah yang sukses dan gagal. Outputnya 5 untuk gagal, 6 untuk sukses, sesuai logika kode tersebut. Jika program di atas dijalankan (setelah disimpan dalam fail bash_return_value_demo.sh), maka hasilnya adalah sebagai berikut, sesuai dengan penjelasan di atas.
./bash_return_value_demo.sh
Value of x: 5
Failure!
Return value: 1
-----------------
Value of x: 6
Failure!
Return value: 1
-----------------
Value of x: 7
Failure!
Return value: 1
-----------------
Value of x: 8
Failure!
Return value: 1
-----------------
Value of x: 9
Failure!
Return value: 1
-----------------
Value of x: 10
Failure!
Return value: 1
-----------------
Value of x: 11
Success!
Return value: 0
-----------------
Value of x: 12
Success!
Return value: 0
-----------------
Value of x: 13
Success!
Return value: 0
-----------------
Value of x: 14
Success!
Return value: 0
-----------------
Value of x: 15
Success!
Return value: 0
-----------------
Number of successful commands: 5
Number of failed commands: 6

Thursday, March 07, 2024

Membuat Alias untuk Github Copilot CLI

Untuk membuat alias untuk Github Copilot, misal ?? untuk menggantikan `gh copilot suggest`, beberapa baris alias berikut dapat ditambahkan pada fail `.bashrc`.
alias '??'='gh copilot suggest -t shell'
alias 'git?'='gh copilot suggest -t git'
alias 'explain'='gh copilot explain'
Dengan cara ini kita bisa mempermudah hidup dan menghemat waktu. Berikut contohnya:
bagus@m049:~$ ?? list WAV files less than 1 MB

Welcome to GitHub Copilot in the CLI!
version 0.5.4-beta (2024-01-04)

I'm powered by AI, so surprises and mistakes are possible. Make sure to verify any generated code or suggestions, and share feedback so that we can learn and improve. For more information, see https://gh.io/gh-copilot-transparency

Suggestion:                                                                     
                                                                                
  find . -name "*.wav" -size -1M                                                

? Select an option
> Exit
bagus@m049:~$ git? show history

Welcome to GitHub Copilot in the CLI!
version 0.5.4-beta (2024-01-04)

I'm powered by AI, so surprises and mistakes are possible. Make sure to verify any generated code or suggestions, and share feedback so that we can learn and improve. For more information, see https://gh.io/gh-copilot-transparency

Suggestion:                                                                     
                                                                                
  git log                                                                       

? Select an option
> Exit
bagus@m049:~$ explain "make -j 5"

Welcome to GitHub Copilot in the CLI!
version 0.5.4-beta (2024-01-04)

I'm powered by AI, so surprises and mistakes are possible. Make sure to verify any generated code or suggestions, and share feedback so that we can learn and improve. For more information, see https://gh.io/gh-copilot-transparency

Explanation:                                                                    
                                                                                
  • make is a build automation tool used to compile and build projects.         
    • -j 5 specifies the maximum number of jobs (parallel tasks) that make can  
    run simultaneously. In this case, it is set to 5.  

Thursday, April 14, 2022

Menemukan dan Menghapus file (ekstensi tertentu, ukuran tertentu)

Menemukan fail

Pola: find [nama-direktori] -name [nama-file]

Contoh

pc060066:~$ find . -name tes.txt
./tes.txt

Tanda titik setelah find menunjukkan current directory (dalam hal ini /home/$USER).

Menemukan dan menghapus fail

Pola: find [nama-direktori] -name [nama-file-yang-dihapus] -delete

Contoh

pc060066:~$ cp tes.txt tes-del.txt
pc060066:~$ find . -name tes-del.txt
./tes-del.txt
pc060066:~$ find . -name tes-del.txt -delete
pc060066:~$ find . -name tes-del.txt
Terlihat file yang dihapus (tes-del.txt) tidak ada setelah perintah di atas.


Menemukan dan menghapus fail ekstensi tertentu

Pola: find [nama-direktori] -name ['*.ext'] -delete

pc060066:~$ mkdir test
pc060066:~$ cd test
pc060066:test$ ls
pc060066:test$ touch test{1..5}.txt
pc060066:test$ ls
test1.txt  test2.txt  test3.txt  test4.txt  test5.txt
pc060066:test$ touch readme.md
pc060066:test$ ls
readme.md  test1.txt  test2.txt  test3.txt  test4.txt  test5.txt
pc060066:test$ find . -name '*.txt'
./test1.txt
./test3.txt
./test2.txt
./test5.txt
./test4.txt
pc060066:test$ find . -name '*.txt' -delete
pc060066:test$ ls *.txt
ls: cannot access '*.txt': No such file or directory
Jangan lupa single quote diantara ekstensi ('*.txt'); untuk ekstensi lainnya tanda quote ini tidak perlu. Contohnya *.wav. Kita juga bisa mencari (dan menghapus) file ekstensi tertentu dengan nama tertentu. Contohnya menemukan (dan menghapus) file dengan nama berakhiran *_cd16k.wav.


Menemukan dan menghapus fail ukuran tertentu

Pola: find [nama-direktori] -name [nama-file-opsional] -size [ukuran, -, +] -delete

Contoh:
pc060066:test$ find . -size 4c
./test8.txt
pc060066:test$ find . -size 4c -delete
pc060066:test$ ls
1001_DFA_ANG_XX.wav  test1.txt  test3.txt  test5.txt  test7.txt
readme.md            test2.txt  test4.txt  test6.txt
pc060066:test$ find . -size -10c # find below 10 bytes
./test6.txt
./test1.txt
./test3.txt
./readme.md
./test2.txt
./test5.txt
./test4.txt
pc060066:test$ find . -size -10c -delete # delete below 10 bytes
pc060066:test$ ls
1001_DFA_ANG_XX.wav  test7.txt
pc060066:test$ find . -size +10c -delete # delete above 10 bytes
pc060066:test$ ls
Jadi tanda "-" untuk kurang dari dan "+" untuk lebih dari ukuran file yang dikehendaki. Tidak ada tanda maka hasilnya pada rentang nilai tersebut. Misal 10c untuk 10 bytes, 10k untuk 10 kilobytes, termasuk 10001 bytes sampai dengan 10999 bytes. 

Menghapus file kosong

Pola: find [nama-direktori] -empy -delete
Contoh:
pc060066:test$ find . -empty
./test10.txt
./test6.txt
./test1.txt
./test3.txt
./test2.txt
./test8.txt
./test5.txt
./test9.txt
./test4.txt
./test7.txt
pc060066:test$ find . -empty -delete
pc060066:test$ ls

Menghapus direktori kosong

Pola: find [nama-direktori] -d -empty -delete 

Contoh:
pc060066:test$ ls -ltr
total 20
drwxrwxr-x 2 bagus bagus 4096  4月 14 15:33 test_dir_5
drwxrwxr-x 2 bagus bagus 4096  4月 14 15:33 test_dir_4
drwxrwxr-x 2 bagus bagus 4096  4月 14 15:33 test_dir_3
drwxrwxr-x 2 bagus bagus 4096  4月 14 15:33 test_dir_2
drwxrwxr-x 2 bagus bagus 4096  4月 14 15:33 test_dir_1
pc060066:test$ find . -type d
.
./test_dir_5
./test_dir_4
./test_dir_2
./test_dir_1
./test_dir_3
pc060066:test$ find . -type d -empty
./test_dir_5
./test_dir_4
./test_dir_2
./test_dir_1
./test_dir_3
pc060066:test$ find . -type d -empty -delete
pc060066:test$ ls
Bedakan dengan perintah sebelumnya untuk file, untuk direktori kita perlu argumen "-type d".

Menemukan dan menghapus kecuali


Pola: find [nama-direktori] not -name [kecuali] -delete

Contoh:
find . not -name "*_mono.wav" -delete
Argumen "not" bisa diganti dengan tanda seru "!" agar lebih singkat. Untuk folder yangt tidak kosong (directory is not empty), kita perlu menggunakan "rm -fr" sebagai pengganti argumen "-delete".
find . -mindepth 1 ! -name "kecuali-direktori1" ! -name "*.py" ! -name "KECUALI.md" ! -name "kecuali-direktori2" -exec rm -rf {} +

Friday, April 07, 2017

Tutorial wget

Definisi
Saya sangat menyukai wget. Ketika saya stuck dengan firefox dan chromium karena keduanya semakin lama semakin berat, biasanya saya berpindah ke konsole dan mendownload semua yang saya inginkan dengan wget. Wget merupakan no-interactive network downloader yang berjalan di terminal Unix. Wget mengambil file dari web (web-get, maybe) dengan protokol http, https dan ftp. Dinamakan non-interaktif karena bisa berjalan dalam proses 'background', artinya user tidak perlu terus menerus login, proses download tetap berjalan, dan bisa mem-pause atau men-start proses download. Berikut adalah tampilan wget ketika saya mendownload suatu file dari internet.

tampilan wget ketika mendownload file

Saturday, September 28, 2013

How-to: Mematikan dan Menyalakan Laptop Secara Otomatis

Laptop saya biasa mati sendiri jam 11 malam untuk tidur, kemudian bangun nyala sendiri pada jam 3.30 dinihari. Tak jarang, laptop saya-lah yang membangunkan saya di pagi hari. Bisakah laptop anda juga begitu? berikut caranya (hanya berjalan pada Ubuntu OS/Linux-based, dan Unix-based yang lain, mungkin Apple Mac juga bisa).

Pertama, salin file berikut dan simpan dengan nama suspend_until.sh, atau anda bisa mendownload-nya di halaman Github saya disini. File tersebut bukan karya saya, saya hanya mendownloadnya dari internet.

#!/bin/bash

# Auto suspend and wake-up script
#
# Puts the computer on standby and automatically wakes it up at specified time
#
# Written by Romke van der Meulen (redge.online@gmail.com)
# Minor mods fossfreedom for AskUbuntu
#
# Takes a 24hour time HH:MM as its argument
# Example:
# suspend_until 9:30
# suspend_until 18:45

# ------------------------------------------------------
# Argument check
if [ $# -lt 1 ]; then
    echo "Usage: suspend_until HH:MM"
    exit
fi

# Check whether specified time today or tomorrow
Related Posts Plugin for WordPress, Blogger...