Fungsi dan Script
Membuat fungsi dan script modular di Bash
Membuat Fungsi
Cara 1: Nama Langsung
my_function() {
echo "Hello from function"
}
my_functionCara 2: Keyword function
function my_function {
echo "Hello from function"
}Parameter Fungsi
greet() {
local name=$1 # $1 = parameter pertama
local age=$2 # $2 = parameter kedua
echo "Halo $name, umur $age"
}
greet "Alice" 25
# Output: Halo Alice, umur 25Return Value
# Fungsi tidak mengembalikan string langsung
# Return hanya untuk exit code (0-255)
sum() {
local a=$1
local b=$2
echo $((a + b)) # Print hasil, capture dengan command substitution
}
result=$(sum 5 3)
echo "Hasil: $result"Local vs Global
#!/bin/bash
global_var="saya global"
my_func() {
local local_var="saya lokal"
global_var="diubah di fungsi"
echo "$local_var"
}
my_func
echo "$global_var" # Output: diubah di fungsi
echo "$local_var" # Output: (kosong, tidak ada)Command Substitution
# Cara modern: $()
current_date=$(date +%Y-%m-%d)
files=$(ls *.txt)
# Cara lama (hindari): backticks
current_date=`date +%Y-%m-%d`Here Document dan Here String
# Here Document (multi-line string)
cat << EOF > config.txt
name=Alice
host=localhost
port=3306
EOF
# Here String (single line)
grep "Alice" <<< "Hello Alice, how are you?"Error Handling
#!/bin/bash
set -euo pipefail
download_file() {
local url=$1
local output=$2
if ! curl -sf "$url" -o "$output"; then
echo "Error: Gagal download $url" >&2
return 1
fi
echo "Download berhasil: $output"
}
# Call dengan error handling
if download_file "https://example.com/file.txt" "file.txt"; then
echo "Proses berhasil"
else
echo "Proses gagal"
exit 1
fiLogging Function
#!/bin/bash
log() {
local level=$1
local message=$2
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] [$level] $message"
}
log "INFO" "Mulai proses"
log "WARN" "Disk hampir penuh"
log "ERROR" "Koneksi gagal"Script Template
#!/bin/bash
set -euo pipefail
# Konfigurasi
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "$0")"
# Fungsi
usage() {
cat << EOF
Usage: $SCRIPT_NAME [OPTIONS]
Options:
-h, --help Tampilkan bantuan
-f, --file Spesifikasi file
-v, --verbose Mode verbose
EOF
exit 0
}
main() {
# Logic utama
echo "Running $SCRIPT_NAME from $SCRIPT_DIR"
}
# Parse argument
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help) usage ;;
-f|--file) shift; file=$1 ;;
-v|--verbose) verbose=1 ;;
*) echo "Unknown option: $1"; exit 1 ;;
esac
shift
done
main "$@"Sourcing File
# Memuat fungsi dan variabel dari file lain
source ./utils.sh
. ./utils.sh # Cara lama (sama dengan source)Trap (Signal Handler)
#!/bin/bash
# Cleanup saat script exit
cleanup() {
echo "Membersihkan temporary files..."
rm -f /tmp/temp_*.txt
}
trap cleanup EXIT
trap 'echo "Interrupted"; exit 1' INT TERM
# Script utama
sleep 10Best Practice
- Gunakan
localuntuk variabel di fungsi - Gunakan
readonlyuntuk konstanta - Selalu gunakan
set -euo pipefail - Quote semua variabel:
"$var" - Pisahkan fungsi ke file terpisah dan source
- Gunakan
trapuntuk cleanup - Return 0 untuk sukses, non-zero untuk error