Passing array to function of shell script - shell

How to pass array as function in shell script?
I written following code:
function test(){
param1 = $1
param2 = $2
for i in ${$param1[#]}
do
for j in ${param2[#]}
do
if($(i) = $(j) )
then
echo $(i)
echo $(j)
fi
done
done
}
but I am getting line 1: ${$(param1)[#]}: bad substitution

There are multiple problems:
you can't have spaces around the = when assigning variables
your if statement has the wrong syntax
array passing isn't right
try not to call your function test because that is a shell command
Here is the fixed version:
myFunction(){
param1=("${!1}")
param2=("${!2}")
for i in ${param1[#]}
do
for j in ${param2[#]}
do
if [ "${i}" == "${j}" ]
then
echo ${i}
echo ${j}
fi
done
done
}
a=(foo bar baz)
b=(foo bar qux)
myFunction a[#] b[#]

You can use the following script accordingly
#!/bin/bash
param[0]=$1
param[1]=$2
function print_array {
array_name=$1
eval echo \${$array_name[*]}
return
}
print_array param
exit 0

A simple way :
function iterate
{
n=${#detective[#]}
for (( i=0; i<n; i++ ))
do
echo ${detective[$i]}
done
}
detective=("Feluda" "Sharlockhomes" "Bomkesh" )
iterate ${detective[#]}

Related

How to assign multiple string values into a variable in shell scripts?

I'm trying to loop a text file changing the number and the hole string is store into a shell variable, to print it latter
I've tried echo the string an the integer (number from the loop) using ">>"
#!/bin/bash
a=0
while [ "$a" -lt 4 ]
do
echo '<div name="block-'${a}'">' >> $sub_main
((a++))
done
echo "done"
echo $sub_main
The output from the script should be:
<div name="block-0">
<div name="block-1">
<div name="block-2">
<div name="block-3">
>> appends the out putto a file. If you want to append to a variable you can use an assignment with the variable to append to at the beginning of the right value.
a=0;
sub_main="";
while [ "${a}" -lt 4 ]; do
sub_main="${sub_main}\n<div name=\"block-${a}\">";
((a++));
done;
echo "done";
echo "${sub_main}";
Or, if the appending to the file was intended, you can simply use cat instead of echo, to output the file's contents.
I.e. replace
echo $sub_main
with:
cat "${sub_main}";
Use command substitution to capture the output into a variable:
#!/bin/bash
sub_main=$(
for (( a = 0; a < 4; a++ )); do
printf '<div name="block-%d">\n' "$a"
done
)
# ... do other stuff ...
echo "$sub_main"
Or you might want to use a function to defer execution until later:
#!/bin/bash
sub_main() {
for (( a = 0; a < 4; a++ )); do
printf '<div name="block-%d">\n' "$a"
done
}
# ... do other stuff ...
sub_main

Call function in shell script

I have the following code, that I want to be inside an function getsum(). I tried with the following code working without the function. When I run ./sum 5 6 I get 11.
#!/bin/bash
sum=0
for i in $#; do sum=$((sum+i)); done
echo $sum
exit 0
But how can I put it in a function doing the same job?
I tried the following code but it doesn't work.
#!/bin/bash
sums() {
sum=0
for i in $#; do sum=$((sum+i)); done
echo $sum
exit 0
}
sums
You just need to pass the arguments ($#) to the function sum() that you pass to your script:
#!/bin/bash
sums() {
sum=0
for i in $#; do sum=$((sum+i)); done
echo $sum
exit 0
}
sums "$#" # Note this line

bash substitution call that increments a variable

I'm trying to define a bash function returning an incremented id
that I can access directly using bash substitution:
#!/bin/bash
getId() {
echo "$x"
x=$((x+1))
}
x=0
echo "id1: $(getId)"
echo "id2: $(getId)"
However the variable is not incremented and I cannot figure out why.
id1: 0
id2: 0
Please, does someone have an explanation for this behaviour?
getId() {
echo "$x"
((x++))
}
x=0
echo -n "id1: "
getId
echo -n "id2: "
getId
Output:
id1: 0
id2: 1
There is no easy way I know of to do it in a sub-shell call using the syntax you have (in the echo line).
An alternate would be:
#!/bin/bash
export x=0
incId() {
#echo "$x"
(( x += 1))
}
incId
echo "id1: $x"
incId
echo "id2: $x"
But here you need the out-of-the-echo-line incId function call to get the id incremented.
It also starts counting from 1, not 0.
Using the let shell command is the better way to do math too.
Using (( ... )) is the right way to do shell arithmetic
Might as well make it generic:
incr() { (( $1 += ${2:-1} )); }
Examples:
incr x ; echo $x # => 1
incr x ; echo $x # => 2
incr x 4; echo $x # => 6
incr x -2; echo $x # => 4

Shell Scripting: Function with multi-line argument as an argument to another function

I have a function which takes another function as an argument and perform some operation.
e.g.
processFunc()
{
Func=$1
...
}
Now the problem is when i am passing a function which also accept multi line variable as argument.
e.g.
VAL="1\n2\n3\n4"
Func1()
{
VAL=$1
...
}
Now, there is no problem when I call direct function Func1()
e.g.
VAL2=`Func1 "$VAL"`
But an issue arises when I try to call proccessFunc()
e.g.
VAL3=`processFunc 'Func1 "$VAL"'` #Here is the problem...
Need help how to resolve the above problem.
Test code
#! /bin/bash
#set -x
func1()
{
VAL1="$1"
echo "$VAL1" ok
for i in $VAL1
do
echo $i
sleep 1
done
}
func2()
{
VALFUN="$1"
TIME=$2
COUNTER=1
while [ $COUNTER -le $TIME ]
do
# clear
$VALFUN
sleep 2
COUNTER=`expr $COUNTER + 1`
done
}
func3()
{
echo a
echo b
echo c
}
#### Main #####
LOCALVAL="`echo -e "123\nabc\nxyz"`"
#echo "$LOCALVAL"
echo "func1"
func1 "$LOCALVAL"
echo "func2 with func3"
func2 "func3" 3
echo "func2 wth func1"
func2 "func1 "$LOCALVAL"" 3
Error I am getting is:
./test.sh: line 18: [: abc: integer expression expected
Wouldn't that be great if you use the output from the Func1 and use it for the processFunc
So your code would be :
VAL="1\n2\n3\n4"
VAL2=Func1 "$VAL"
Where Func1 would be :
Func1()
{
VAL=$1
...
}
And then calling the processFunc as
VAL3=processFunc "$VAL"
Hope this helps.
Or Else what I suppose is that you are passing a string value where your shell is expecting a string.
And I believe the code should be :
a=123\nabc\nxyz
LOCALVAL = echo $a
You can do like this
VAL3="processFunc Func1 $VAL"
$VAL3

How to pass positional parameters to a function

I was trying things with bash scripts. I made this simple script
#!/bin/bash
function myfun()
{
for item in `seq 1 5`
do
echo "$item $1 $2"
done
}
myfun
but no luck. If I change it like this as below, everything seems to be fine,
#!/bin/bash
a=$1
b=$2
function myfun()
{
for item in `seq 1 5`
do
echo "$item $a $b"
done
}
myfun
It looks like arguments (positional parameters) do not work inside function in shell. Am I doing any mistake? I am still learning things. So can you explain why is it so?
It's the function not the loop:
function myfun()
{
for item in `seq 1 5`
do
echo "$item $1 $2"
done
}
# Pass all of the script's parameters to the function,
# as if writing myfun "$1" "$2" "$3"..
myfun "$#"
Inside a function, $1 and $2 give the function arguments and not the script parameters.
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html

Resources