Reputation: 57
For some reason in the code below for loop treats args as array and wc -l can count the lines correctly but I can't get the $(#args[@]) to produce the correct count
function doSomthing() {
local i args a
args=$1;
a=("1" "2" "3" "4");
i=0
echo wc =`wc -l <<< "$args"`;
for arg in $args; do
((i++))
echo "$i"
done;
echo i = $i
echo a = ${#a[@]}
echo args = ${#args[@]}
echo $args
}
The output of this function is
$> doSomthing $'1\n2\n3\n4'
wc = 4
1
2
3
4
i = 4
a = 4
args = 1
1 2 3 4
Upvotes: 0
Views: 52
Reputation: 57
Problem solved!
I just needed to put $1 inside parenthesis.
For some reason when I tried it before it did not work but now it does.
Here is the new code:
function doSomthing () {
local i args a;
args=( $1 );
a=("1" "2" "3" "4");
i=0;
echo wc =`wc -l <<< "$args"`;
for arg in $args; do
((i++));
echo "$i";
done;
echo i = $i;
echo a = ${#a[@]};
echo args = ${#args[@]};
echo ${args[@]}
}
And here is the new output:
$> doSomthing $'1\n2\n3\n4'
wc = 1
1
i = 1
a = 4
args = 4
1 2 3 4
Cheers ;-)
Upvotes: 0
Reputation: 531165
args
is not an array; it is simply a string that contains embedded newlines. That means, if you try to treat it as an array, it will appear as if you defined it as
args=( $'1\n2\n3\4' )
not
args=(1 2 3 4)
Upvotes: 4