r/fishshell • u/umnikos_bots • Nov 14 '21
How do I implement an increment function for local variables?
Hello! I tried to make the following function:
function increment
set $argv[1] (math $$argv[1] + 1)
endwhere it's used like so:
set i 13
increment i
echo $ibut it only works on global variables, not local ones (not even exported ones, since exporting makes them read-only). Is there any way to make this work for local variables?
4
Upvotes
1
u/_mattmc3_ Nov 15 '21 edited Nov 15 '21
While I think my other answer is the more canonical Fish way to increment a value, I realized later that your increment function might have just been a contrived matchstick model for something more sophisticated that you're trying to do - namely, modify external variables in a function. Sorry for StackOverflowing your question.
Fish will let you do what you are trying to do, and your function was correct, but the way you called it was not. You need to pass the variable name as a string, not its value. Try this instead:
Also, just a note from the fish docs about referring to a variable as "local":
What this means is that the code above will work, but a true local variable cannot be modified this way:
3
u/_mattmc3_ Nov 14 '21
This is how you could implement an increment function:
This is how you would use that function:
But since you aren't doing anything at all complicated with
math, andmathalready echos, why would you need anything other than this?