In this tutorial, we will learn how to create a function in a Bash shell script. Functions can help automate repetitive tasks and improve the efficiency of your workflow.
Introduction
As a developer, I often find myself performing the same actions repeatedly. Instead of manually executing these actions each time, I decided to write a shell script to automate the process. One particular task required me to navigate through different folders and execute three commands using npx
. To simplify my script and make it more maintainable, I decided to create a function.
Creating the Function
To start, let’s encapsulate the npx
commands within a function. Open your shell script and add the following code:
generate_book() {
npx honkit pdf ./ ../books/$(basename $PWD).pdf
npx honkit epub ./ ../books/$(basename $PWD).epub
npx honkit mobi ./ ../books/$(basename $PWD).mobi
}
The generate_book()
function encapsulates the npx
commands and defines a reusable block of code. This will make our script more concise and easier to maintain.
Using the Function
Next, we need to incorporate the function into our script. We can utilize a loop to iterate through an array of book folders.
books=( "c-handbook" "css-handbook" "deno-handbook" "es5-to-next" "express-handbook" "html-handbook" "javascript-beginner-handbook" "linux-commands-handbook" "nextjs-handbook" "node-handbook" "python-handbook" "react-beginner-handbook" "svelte-handbook" "vue-handbook" )
for i in "${books[@]}"
do
echo $i
cd $i
generate_book
cd ..
done
In the code snippet above, we declare an array called books
containing the names of our book folders. The loop iterates through each item in the books
array, sets the current book directory using cd
, calls our generate_book()
function, and then returns to the parent directory.
Conclusion
By encapsulating repetitive commands within a function, we can make our shell scripts more modular and reusable. This approach improves code readability, reduces duplication, and simplifies maintenance.
Feel free to modify the generate_book()
function or add additional functionality to suit your specific needs.
Tags: bash scripting, shell script, automation, function