Reputation: 198
I was expecting this code to produce
A
A A
A A A A
A A A A A A A A
.....
But instead I get
A
A
A
A
...
Code :
fun() {
var=$1
echo $var #for debugging
var=$var" "$var
fun $var
}
fun "A"
Can you please explain me why and how to get the expected output ?
See above .
Upvotes: 1
Views: 90
Reputation: 785186
You don't need to store $1
in a variable and need quotes around function argument.
This function should work for you:
fun() {
[[ ${#1} -gt 20 ]] && return # bail out when length is > 20
echo "$1" # echo passed value
fun "$1 $1" # call function recursively
}
Test:
fun "*"
*
* *
* * * *
* * * * * * * *
fun "A"
A
A A
A A A A
A A A A A A A A
If you want to increment one character in each row in output then use:
fun() {
[[ ${#1} -gt 20 ]] && { unset var; return; } # bail out & unset var
[[ -z $var ]] && var="$1" # set var first time
echo "$1" # echo passed value
fun "$var $1" # recursive call
}
Upvotes: 0
Reputation: 34474
A simplified function definition:
$ fun() { echo "$1"; fun "$1 $1"; }
$ fun "A" | head -6
A
A A
A A A A
A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
NOTES:
A's
is treated as a single stringhead -6
is used here to keep from going into an infinite loopOne idea for limiting the recursion depth would be to keep track of a recursion level, either hardcoded in the function or possibly as an additional argument to the function call; one idea for implementing the latter:
$ fun() { echo "$1"; [[ "$2" -le 1 ]] && return; fun "$1 $1" $(($2-1)) ; }
$ fun "A" 6
A
A A
A A A A
A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
NOTES:
A's
and the number in the 'last' position)${2:-4}
==> default 1st call to using 4
)Upvotes: 0
Reputation: 185161
Reusing the most of your code as possible (need to add quotes properly):
fun() {
var=$1
echo "$var" # for debugging
var="$var $var" # look the quote style
((${#var} > 50)) && return # avoid infinite recursion
fun "$var"
}
fun "A"
Learn how to quote properly in shell, it's very important :
"Double quote" every literal that contains spaces/metacharacters and every expansion:
"$var"
,"$(command "$var")"
,"${array[@]}"
,"a & b"
. Use'single quotes'
for code or literal$'s: 'Costs $5 US'
,ssh host 'echo "$HOSTNAME"'
. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words
when-is-double-quoting-necessary
A
A A
A A A A
A A A A A A A A
A A A A A A A A A A A A A A A A
Upvotes: 1
Reputation: 16762
The other answers seem to be addressing the infinite recursion but not why the output is not as expected.
The reason you only get A
instead of A A
, A A A A
, etc, is simply that you call fun $var
instead of fun "$var"
.
Because, $var
contains whitespace, if you do not quote it, it gets split (into $1
, $2
, $3
, etc) instead of remaining as a single argument.
Upvotes: 1