#function hello world defined
fnHelloWorld()
{
#print hello world
echo "Hello World";
}
#calling hello world function
fnHelloWorld
Code language: Bash (bash)
Output The above shell script will print Hello World on command prompt. All we have done is we have defined a function in shell script byCode language: Bash (bash)$./helloworld.sh Hello World
fnHelloWorld() {}
and called this by just fnHelloWorld. fnArgumentFunction()
{
echo "Argument 1:" . $1
echo "Argument 2:" . $2
}
fnArgumentFunction "Hello" "World"
Code language: Bash (bash)
Thus if your function will use three arguments you can just use $1, $2 and $3 in your code. You may want to use $# which gives you number of arguments passed to the function if you want to implement a function with variable arguments. fnReturnFunction()
{
echo $1$2
}
value=$(fnReturnFunction "holly" "wood")
Code language: Bash (bash)
Note that in above example we have called the function by $(fnReturnFunction “holly” “wood”). Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
Capturing echoed output is fairly useful, but then obtaining the success or failure of the function can get tricky. I might write it like this:
myfunc() {
local var=$1
eval $var="$2$3"
}
This makes it handy to test the return value of a function that might fail:
if myfunc value "holly" "wood"; then
echo "$value beckons!"
else
echo woe is me
fi
Damn, it backslashed all the quotes and backslashes :\
Hi spacebat.. I resolved the backslash issue. Thanks for the code.
My method suffers from increased need for quoting (say the parameters have spaces, you might need to quote them and escape the quotes before passing to eval), also it won't work if the variable name you pass in is the same name as the local variable used to store the name, ie this is broken:
myfunc var "holly" "wood"
I've never run into that problem in real life, but I've been reading about it in the context of lisp macros where its known as variable capture. A workaround would be to prefix local vars with underscores.
Anyway at this point I tend to think heck this needs porting to perl or python :)
Neat!
could you please cover some basic like this on awk and sed. wil so thankful
nice 1......