Kumpulan skrip Bash untuk mengotomatiskan tugas rutin dan merampingkan alur kerja Anda. Dari penggantian nama file sederhana hingga penerapan yang lebih kompleks, skrip Bash ini siap membantu Anda.
Hello world #
Contoh sederhana dari skrip Bash untuk mencetak string “Hello World” ke output standar (stdout).
#!/usr/bin/env bash
echo "Hello world"
Untuk menjalankan skrip, Anda perlu membuka terminal pada direktori tempat skrip berada.
chmod u+x filename.sh
./filename.sh
Di baris pertama skrip, shebang (#!) digunakan untuk menentukan bahasa yang akan digunakan saat skrip dieksekusi. contoh yang paling umum digunakan adalah
#!/usr/bin/env bash
, #!/usr/bin/env perl
, #!/usr/bin/env python3
.
Variables #
Variabel dapat menyimpan nilai dari perintah yang dieksekusi.
user=$(whoami)
Cek output dari variable user dengan cara.
echo $user
If statements #
If statements digunakan untuk mengeksekusi blok kode jika kondisi tertentu terpenuhi.
Perlu diperhatikan jika penerapan untuk string dan int berbeda.
if [ $i -eq 10 ]; then echo True; fi # int comparison
if [ "$name" == "10" ]; then echo True; fi # string comparison
Integer comparison:
Operator | Description |
---|---|
-eq |
equal |
-ne |
not equal |
-gt |
greater than |
-ge |
greater than or equal to |
-lt |
less than |
-le |
less than or equal to |
String comparison:
Operator | Description |
---|---|
== |
equal |
!= |
not equal |
> |
greater than |
< |
less than |
-n |
string is not null |
-z |
string is null |
Contoh skrip dengan if statements.
#!/usr/bin/env bash
echo -n "name :"
read name;
if [ "$name" == "cicak" ]; then echo Sip, Anda adalah cicak; fi
Saat menjalankan skrip, Anda harus mengisikan name
dan apabila kondisi name
terpenuhi akan menghasilkan output dari perintah echo
.
$ bash filename
name :cicak
Sip, Anda adalah cicak
$
Sebaliknya jika kondisi tidak terpenuhi maka tidak mengeluarkan output.
$ bash filename
name :robot
$
Loops #
Ada empat tipe loop di Bash: for
, while
, until
dan select
.
for loops #
For loop digunakan untuk mengulangi urutan langkah beberapa kali. contoh sederhananya.
for number in {1..10}
do
echo "$number "
done
Ketika skrip dijalankan maka akan menghasilkan output angka 1 sampai 10.
while loop #
While loop menguji suatu kondisi dan mengulang urutan perintah selama kondisi itu benar.
#!/bin/bash
# Squares of numbers from 0 through 9
x=0
while [[ $x -lt 10 ]]; do # value of x is less than 10
echo $(( x * x ))
x=$(( x + 1 )) # increase x
done
until loop #
until [[ condition ]]; do
#statements
done
select loop #
Select loop digunakan untuk mengatur user menu. Ini memiliki sintaks yang hampir sama dengan for loop.
#!/bin/bash
PS3="Choose the package manager: "
select ITEM in bower npm gem pip
do
echo -n "Enter the package name: " && read PACKAGE
case $ITEM in
bower) bower install $PACKAGE ;;
npm) npm install $PACKAGE ;;
gem) gem install $PACKAGE ;;
pip) pip install $PACKAGE ;;
esac
break # avoid infinite loop
done
Output ketika skrip dijalankan.
$ ./my_script
1) bower
2) npm
3) gem
4) pip
Choose the package manager: 2
Enter the package name: bash-handbook
<installing bash-handbook>
Arrays #
Array adalah variabel yang menyimpan daftar nilai yang diurutkan. Nilai dipisahkan oleh spasi.
array=(1 2 3 4 5)
Contoh skrip Untuk mengulangi elemen array.
items=('item_1' 'item_2' 'item_3' 'item_4')
for item in "${items[@]}"; do
echo "$item"
done
Saat skrip dijalankan outputnya adalah nilai yang pada array.
$ bash filename
item_1
item_2
item_3
item_4
$
Functions #
Functions digunakan untuk mengelompokkan urutan perintah menjadi satu unit. Mereka digunakan untuk melakukan tugas yang berulang. Fungsi dapat dipanggil dari mana saja di skrip.
Contoh berikut membuat fungsi bernama hello_world
yang mencetak string Hello World ke output standar (stdout):
hello_world()
{
echo "Hello World!"
}
Untuk menjalankan skrip, gunakan perintah source
.
source filename
Lalu panggil function.
$ hello_world
Hello World!
Example 1
create_invoice()
{
case "$1" in
--list)
;;
--uuid)
uuid="$2"
;;
esac
## your command
## clear variable
unset droplet
unset volume
}
Jalankan skrip dengan perintah source
lalu panggil function seperti berikut.
create_invoice --uuid 1234
Example 2
create_instance()
{
while [[ $# -gt 0 ]]; do
case "$1" in
--name)
name="$2"
shift 2
;;
--size)
size="$2"
shift 2
;;
--region)
region="$2"
shift 2
;;
--image)
image="$2"
shift 2
;;
--ipv6)
ipv6="$2"
shift 2
;;
--vpc)
vpc="$2"
shift 2
;;
*)
echo "Argumen tidak valid: $1"
exit 1
;;
esac
done
## your command
## clear variable
unset name
unset size
unset region
unset image
unset ipv6
unset vpc
}
Contoh skrip yang mendefinisikan dan menggunakan fungsi untuk menjumlahkan dua angka.
#!/usr/bin/env bash
sum_two()
{
return $(($1 + $2))
}
sum_two 5 3
echo $?
Jalankan skrip.
bash filename
Redirections #
Bash memiliki operator redirect >
yang dapat digunakan untuk mengontrol ke mana hasil output dikirim.
some_command > out.log # Redirect stdout to out.log
some_command 2> err.log # Redirect stderr to file err.log
some_command 2>&1 # Redirect stderr to stdout
some_command 1>/dev/null 2>&1 # Silence both stdout and stderr
Contoh skrip untuk menyimpan output dari command ke dalam file log.
#!/bin/bash
LOG_FILE=${1:-/root/ips.txt}
log() {
echo "$(date -u): $*" >> "${LOG_FILE}"
}
ipcek() {
shell=$(/usr/sbin/ifconfig)
log "$shell"
}
ipcek
Available scripts #
Intro #
# | Description | Code |
---|---|---|
1 | Prints “Hello, world!” to the console. | Bash |
2 | Demonstrates the use of if statements to determine if a condition is true or false. | Bash |
3 | Shows the use of a while loop to execute a block of code repeatedly. | Bash |
4 | Demonstrates the use of a for loop to iterate over a sequence of elements. | Bash |
5 | Displays the digits of a given number, one digit per line. | Bash |
6 | Prints all of the numbers within a specified range, one number per line. | Bash |
7 | Prints a Christmas tree pattern to the console. | Bash |
8 | Prompts the user for a response to a given question and stores their response in a variable. | Bash |
Math #
# | Description | Code |
---|---|---|
1 | Performs basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers. | Bash |
2 | Calculates the sum of all the arguments passed to it, treating them as numbers. | Bash |
3 | Converts a number from the decimal (base 10) system to its equivalent in the binary (base 2) system. | Bash |
4 | Calculates the factorial of a given integer. | Bash |
5 | Determines whether a given number is a prime number or not. | Bash |
6 | Calculates the square root of a given number. | Bash |
Strings #
# | Description | Code |
---|---|---|
1 | Counts the number of times a specific character appears in a given string. | Bash |
2 | Converts all uppercase letters in a given string to lowercase. | Bash |
3 | Converts all lowercase letters in a given string to uppercase. | Bash |
4 | Checks if a given string is a palindrome, i.e., a word that is spelled the same way forwards and backwards. | Bash |
5 | Checks if two given strings are anagrams, i.e., if they are made up of the same letters rearranged in a different order. | Bash |
6 | Calculates the Hamming Distance between two strings, i.e., the number of positions at which the corresponding characters are different. | Bash |
7 | Sorts a given string alphabetically, considering all letters to be lowercase. | Bash |
Array #
# | Description | Code |
---|---|---|
1 | Calculates the arithmetic mean of a given list of numbers. | Bash |
2 | Finds the maximum value in a given array of numbers. | Bash |
3 | Finds the minimum value in a given array of numbers. | Bash |
4 | Removes duplicates from a given array of numbers. | Bash |
Files #
# | Description | Code |
---|---|---|
1 | Counts the number of files in a specified directory. | Bash |
2 | Creates a new directory with a specified name. | Bash |
3 | Counts the number of lines in a specified text file. | Bash |
4 | Gets the middle line from a specified text file. | Bash |
5 | Removes duplicate lines from a specified file. | Bash |
6 | Replaces all forward slashes with backward slashes and vice versa in a specified file. | Bash |
7 | Adds specified text to the beginning of a specified file. | Bash |
8 | Removes all lines in a specified file that contain only whitespaces. | Bash |
9 | Renames all files in a specified directory with a particular extension to a new extension. | Bash |
10 | Strips digits from every string found in a given file. | Bash |
11 | Lists the most recently modified files in a given directory. | Bash |
System administration #
# | Description | Code |
---|---|---|
1 | Retrieves basic system information, such as hostname and kernel version. | Bash |
2 | Determines the type and version of the operating system running on the machine. | Bash |
3 | Checks whether the current user has root privileges. | Bash |
4 | Checks if the apt command, used for package management on Debian-based systems, is available on the machine. | Bash |
5 | Retrieves the size of the machine’s random access memory (RAM). | Bash |
6 | Gets the current temperature of the machine’s central processing unit (CPU). | Bash |
7 | Retrieves the current overall CPU usage of the machine. | Bash |
8 | Blocks certain websites from being visited on the local machine by modifying the hosts file. | Bash |
9 | Creates a backup of the system’s files, compress the backup, and encrypt the resulting archive for storage. The backup can be used to restore the system in case of data loss or system failure. | Bash |
10 | Displays processes that are not being waited on by any parent process. Orphan processes are created when the parent process terminates before the child process. | Bash |
11 | Displays processes that are in an undead state, also known as a “zombie” state. Zombie processes are processes that have completed execution but still have an entry in the process table. | Bash |
Programming workflow #
# | Description | Code |
---|---|---|
1 | Removes the carriage return character (\r ) from the given files, which may be present in files transferred between systems with different line ending conventions. |
Bash |
2 | Replaces all characters with diacritical marks in the given files with their non-diacritical counterparts. Diacritical marks are small signs added above or below letters to indicate different pronunciations or tones in some languages. | Bash |
3 | Changes all spaces in file names to underscores and convert them to lowercase. This can be useful for making the file names more compatible with systems that do not support spaces in file names or for making the file names easier to read or type. | Bash |
4 | Removes any trailing whitespace characters (spaces or tabs) from the end of every file in a given directory. Trailing whitespace can cause formatting issues or interfere with certain tools and processes. | Bash |
5 | Formats and beautify every shell script found in the current repository. This can make the scripts easier to read and maintain by adding consistent indentation and whitespace. | Bash |
6 | Finds functions and classes in a Python project that are not being used or called anywhere in the code. This can help identify and remove unnecessary code, which can improve the project’s performance and maintainability. | Bash |
Git #
# | Description | Code |
---|---|---|
1 | Resets the local repository to match the state of the remote repository, discarding any local commits and changes. This can be useful for starting over or synchronizing with the latest version on the remote repository. | Bash |
2 | Deletes the specified branch both locally and on the remote repository. This can be useful for removing branches that are no longer needed or for consolidating multiple branches into a single branch. | Bash |
3 | Counts the total number of lines of code in a git repository, including lines in all branches and commits. This can be useful for tracking the size and complexity of a project over time. | Bash |
4 | Combines multiple commits into a single commit. This can be useful for simplifying a commit history or for cleaning up a series of small, incremental commits that were made in error. | Bash |
5 | Removes the n last commits from the repository. This can be useful for undoing mistakes or for removing sensitive information that was accidentally committed. |
Bash |
6 | Changes the date of the last commit in the repository. This can be useful for altering the commit history for cosmetic purposes. | Bash |
7 | Downloads all of the public repositories belonging to a specified user on GitHub. This can be useful for backing up repositories. | Bash |
8 | Squashes all commits on a specified Git branch into a single commit. | Bash |
9 | Counts the total lines changed by a specific author in a Git repository. | Bash |
Utility #
# | Description | Code |
---|---|---|
1 | Finds the public IP address of the device running the script. | Bash |
2 | Deletes all files in the trash bin. | Bash |
3 | Extracts files with a specified extension from a given directory. | Bash |
4 | Determines which programs are currently using a specified port number on the local system. | Bash |
5 | Converts month names to numbers and vice versa in a string. For example, “January” to “1” and “1” to “January”. | Bash |
6 | Creates command aliases for all the scripts in a specified directory, allowing them to be run by simply typing their names. | Bash |
7 | Generates a random integer within a given range. The range can be specified as arguments to the script. | Bash |
8 | Generates a random password of the specified length, using a combination of letters, numbers, and special characters. | Bash |
9 | Measures the time it takes to run a program with the specified input parameters. Output the elapsed time in seconds. | Bash |
10 | Downloads the audio from a YouTube video or playlist in MP3 format. Specify the video or playlist URL and the destination directory for the downloaded files. | Bash |
11 | Clears the local caches in the user’s cache directory (e.g. ~/.cache ) that are older than a specified number of days. |
Bash |