Bash Shell adalah bahasa skrip yang populer dan fleksibel untuk digunakan dalam menjalankan serangkaian tugas seperti otomatisasi, managemen sistem, dan pengelolaan data.
Agar dapat mengikuti beberapa contoh skrip pada artikel ini, buatlah file untuk menulis skrip dan berikan tambahan permission chmod u+x
agar file skrip dapat dieksekusi
seperti ./filename
Reading Input from User
Perintah read
dapat membantu dalam membaca input dari user atau dari input standar stdin
#!/usr/bin/env bash
# Untuk membaca input dari user dan mamasukannya ke dalam variabel username
echo "Enter Username: "
read username
echo $username
# Menampilkan prompt menggunakan perintah read
# -p singkatan dari prompt
# membaca input dari user dan memasukannya ke dalam variabel newusername
read -p "Enter the new username: " newusername
echo $newusername
# membaca input dari user dan disembunyikan agar tidak terbaca di prompt terminal.
# -s singkatan dari silent
read -sp "Enter Password: " password
echo ""
echo $password
Command Substitution
Command substitution memungkinkan output dari perintah untuk diganti sebagai nilai ke dalam variabel. Hal ini dapat dilakukan dengan menggunakan backticks (`) atau tanda dollar ($).
#!/usr/bin/env bash
echo "Method 1 - mengunanakn backticks"
working_dir=`pwd`
echo $working_dir
echo "Method 2 - menggunakan tanda dollar"
working_dir=$(pwd)
echo $working_dir
Argument Passing
Argument Passing adalah variabel khusus seperti $1
, $2
,$3
dan lainnya seperti
- $0 - mengembalikan nama file skrip shell.
- $@ - mengembalikan semua argumen yang diteruskan dari cli.
- $# - mengembalikan jumlah argumen yang diteruskan dari cli.
Contoh skrip.
#!/bin/bash
# gives the filename of the script itself
echo "FileName Argument: "$0 # filename.sh
# gives the first argument passed
echo "First Argument: "$1 # Vish
# gives the second argument passed
echo "Second Argument: "$2 # DevOps Engineer
# displays all arguments passed
echo "All Arguments: "$@ # Vish DevOps Engineer
# displays number of arguments passed
echo "No of Arguments: "$# # 2
Selanjutnya jalankan file skrip.
filename.sh "Vish" "DevOps Engineer"
Arithmetic Operations
Gunakan tanda kurung ganda (())
untuk melakukan operasi aritmatika.
#!/bin/bash
n1=10
n2=5
echo "Sum of two numbers: "$(($n1+$n2)) # Addition
echo "Sub of two numbers: "$(($n1-$n2)) # Substraction
echo "Mul of two numbers: "$(($n1*$n2)) # Mulitplication
echo "Div of two numbers: "$(($n1/$n2)) # Division
echo "Modulus of two numbers: "$(($n1%$n2)) # Modulus
Conditionals
Untuk menerapkan argumen kondisional gunakan tanda [[]]
. Berikut adalah beberapa definisi yang dapat digunakan untuk menguji kondisi.
Conditions
[[ -z STRING ]]
- Empty string[[ -n STRING ]]
- Not empty string[[ STRING == STRING ]]
- Equal[[ STRING != STRING ]]
- Not equal[[ NUM -eq NUM ]]
- Equal[[ NUM -ne NUM ]]
- Not equal[[ NUM -lt NUM ]]
- Less than[[ NUM -le NUM ]]
- Less than or equal[[ NUM -gt NUM ]]
- Greater than[[ NUM -ge NUM ]]
- Greater than or equal[[ ! EXPR ]]
- Not[[ X && Y ]]
- And[[ X || Y ]]
- Or
File Conditions
[[ -e FILE ]]
- Exists[[ -r FILE ]]
- Readable[[ -h FILE ]]
- Symbolic link[[ -d FILE ]]
- Directory[[ -w FILE ]]
- Writable file[[ -s FILE ]]
- File size is > 0 bytes[[ -f FILE ]]
- File[[ -x FILE ]]
- Executable file
#!/bin/bash
a=10
b=20
# less than using square brackets
if [[ $a -lt $b ]]
then
echo "a is less than b"
else
echo "a is not less than b"
fi
# less than using test command
if test "$a" -lt "$b"
then
echo "a is less than b"
else
echo "a is not less than b"
fi
Loops
if else
if else adalah pernyataan kondisional yang memungkinkan eksekusi perintah berbeda berdasarkan kondisi true/false.
#!/bin/bash
# -e stands for exists
if [[ -e ./ifelse.sh ]]
then
echo "File exists"
else
echo "File does not exist"
fi
elif
elif merupakan kombinasi dari else dan if. Ini digunakan untuk membuat beberapa pernyataan kondisional dan harus selalu digunakan bersama dengan pernyataan if else.
#!/bin/bash
read -p "Enter the number between 1 to 3: " number
if [[ $number -eq 1 ]]
then
echo "The number entered is 1"
elif [[ $number -eq 2 ]]
then
echo "The number entered is 2"
elif [[ $number -eq 3 ]]
then
echo "The number entered is 3"
else
echo "Invalid Number"
fi
for
for loop digunakan untuk mengulangi urutan nilai.
#!/bin/bash
for i in {1..10}
do
echo "Val: $i"
done
# C style/Old Style of for loop
for((i=0;i<=10;i++))
do
echo "Val: $i"
done
while
while loop digunakan untuk menjalankan serangkaian perintah berulang kali selama kondisi tertentu benar. Perulangan berlanjut hingga kondisinya salah.
#!/bin/bash
count=0
while [ $count -lt 5 ]
do
echo $count
count=$(($count+1))
done
until
until loop dalam skrip shell digunakan untuk mengeksekusi blok kode berulang kali hingga kondisi tertentu terpenuhi.
#!/bin/bash
count=1
until [ $count -gt 5 ]
do
echo $count
count=$(($count+1))
done
Arrays
Array adalah variabel yang dapat menampung banyak nilai dalam satu nama.
${arrayVarName[@]}
- menampilkan semua nilai array.${#arrayVarName[@]}
- menampilkan panjang array.${arrayVarName[0]}
- menampilkan elemen pertama array.${arrayVarName[-1]}
- menampilkan elemen terakhir array.unset arrayVarName[2]
- menghapus 2 elemen.
#!/bin/bash
# Declare an array of fruits
fruits=("apple" "banana" "orange" "guava")
# Print the entire array
echo "All fruits using @ symbol: ${fruits[@]}"
echo "All fruits using * symbol: ${fruits[*]}"
# Print the third element of the array
echo "Third fruit: ${fruits[2]}"
# Print the length of the array
echo "Number of fruits: ${#fruits[@]}"
Break Statement
break adalah control statement yang digunakan untuk keluar dari perulangan (for, while, or until) ketika kondisi tertentu terpenuhi.
#!/bin/bash
count=1
while true
do
echo "Count is $count"
count=$(($count+1))
if [ $count -gt 5 ]; then
echo "Break statement reached"
break
fi
done
Continue statement
continue digunakan dalam perulangan (for, while, or until) untuk melewati perulangan saat ini dan melanjutkan ke perulangan berikutnya.
#!/bin/bash
for i in {1..10}
do
if [ $i -eq 5 ]
then
continue
fi
echo $i
done
Functions
Fungsi adalah blok kode yang dapat digunakan berulang kali untuk melakukan tugas tertentu.
Normal Function
#!/bin/bash
sum(){
echo "The numbers are: $n1 $n2"
sum_val=$(($n1+$n2))
echo "Sum: $sum_val"
}
n1=$1
n2=$2
sum
Function with return values
Untuk mengakses nilai return yang ada di dalam function bisa menggunakan $?
#!/bin/bash
sum(){
echo "The numbers are: $n1 $n2"
sum_val=$(($n1+$n2))
echo "Sum: $sum_val"
return $sum_val
}
n1=$1
n2=$2
sum
echo "Retuned value from function is $?"
Variables
Variabel adalah pengganti untuk menyimpan nilai yang nantinya dapat diakses menggunakan nama tersebut. Ada dua jenis variabel
Global
- Variabel yang digunakan diluar fungsi dan dapat diakses di seluruh skrip.Local
- Variabel didefinisikan di dalam suatu fungsi dan hanya dapat diakses didalamnya.
#!/bin/bash
# x & y are global variables
x=10
y=20
sum(){
sum=$(($x+$y))
echo "Global Variable Addition: $sum"
}
sum
sub(){
# a & b are local variables
local a=20
local b=10
local sub=$(($a-$b))
echo "Local Variable Substraction: $sub"
}
sub
Dictionaries
Dalam skrip shell, kamus diimplementasikan menggunakan array asosiatif. Array asosiatif adalah array yang menggunakan string sebagai index, bukan bilangan bulat.
#!/bin/bash
# declare a associative array
declare -A colours
# add key value pairs
colours['apple']=red
colours['banana']=yellow
colours['orange']=orange
colours['guava']=green
colours['cherry']=red
echo "Size of dict: ${#colours[@]}"
echo "Color of apple: ${colours['apple']}"
echo "All dict keys: ${!colours[@]}"
echo "All dict values: ${colours[@]}"
# Delete cherry key
unset colours['cherry']
echo "New dict: ${colours[@]}"
# iterate over keys
for key in ${!colours[@]}
do
echo $key
done
# iterate over values
for value in ${colours[@]}
do
echo $value
done
Set Options — The Saviour
Perintah set
memungkinkan untuk mengubah atau menampilkan nilai opsi shell. Anda dapat menggunakannya untuk mengatifkan & menonaktifkan opsi shell tertentu.
set -x
ini seperti mode debug. perintah apapun yang sedang dijalankan akan dicetak terlebih dahulu kemudian output dari perintah akan ditampilkan.