Sep 18, 2023 by Frederic Hallot | 609 views
https://cylab.be/blog/285/building-your-bash-toolkit-creating-a-dynamic-argument-processor-in-bash
In the inaugural blog post of our Building Your Bash Toolkit series, we embarked on a journey to simplify our Bash interactions. Today, we dive deeper, introducing a utility function, process_args
, that seamlessly merges both direct and piped inputs.
process_args
The process_args
function empowers us to determine whether our bash function receives input through a pipe or directly as arguments. This integration helps us write more versatile Bash functions.
process_args() {
local function_name="$1"
shift
if [ -p /dev/stdin ]; then
local piped_data
IFS= read -r piped_data
"$function_name" "$piped_data" "$@"
else
"$function_name" "$@"
fi
}
Now, let’s incorporate process_args
into our toolkit by appending it to 01-basic-tools.sh
:
echo 'process_args() {
local function_name="$1"
shift
if [ -p /dev/stdin ]; then
local piped_data
IFS= read -r piped_data
"$function_name" "$piped_data" "$@"
else
"$function_name" "$@"
fi
}' >> ~/bash-tools/01-basic-tools.sh
simple_printer
To demonstrate the power of process_args
, let’s integrate it directly within a function named simple_printer
:
simple_printer() {
process_args _inner_simple_printer "$@"
}
_inner_simple_printer() {
# Printing all arguments separated by space
echo "$@"
}
Appending to our toolkit:
echo 'simple_printer() {
process_args _inner_simple_printer "$@"
}
_inner_simple_printer() {
echo "$@"
}' >> ~/bash-tools/999-test.sh
Our enhanced function can now gracefully handle both directly given arguments and piped data without explicitly calling process_args
:
# Test with direct arguments:
simple_printer "hello" "world"
# Test with piped input and direct argument:
echo "hello" | simple_printer "world"
With the process_args
utility seamlessly integrated, our bash toolkit is one step closer to scripting nirvana. Functions can now dynamically accept both piped and direct inputs, providing a more streamlined Bash experience.
The journey of building an efficient Bash toolkit involves continuous learning and refinements. The process_args
function is just one of the many tools that, when wielded effectively, can significantly boost our scripting prowess.
Our journey doesn’t stop here. Up next, we’ll be demystifying the art of extracting values from key-value pairs, right from the terminal. By introducing the extract_value
function in our next blog post, we’ll leverage the prowess of process_args
and further our toolkit’s capabilities. Stay tuned and let’s continue refining our Bash experience! Stay tuned!
This blog post is licensed under CC BY-SA 4.0