0

I am working in Ubuntu Shell, but i want it to work for UNIX also.
Here is my code:

#!/bin/bash

func()
{
    x=42
}

x=9
func
echo $x
  • Why is global x changed to 42 when i changed only local variable x
  • Is in unix different rule for variable scopes?
  • Is there a method how to set return value from func to global variable, which can be used later in code?

Thank you!

3

1 Answer 1

0

First, you're not programming Linux; you're actually writing a function for the shell program called bash. Enter info bash on the command line to get documentation for that. For any version of Unix, what happens on the command line depends on which type of shell you're running (there are many; bash is the default for most Linux systems).

Variables in a function which are not declared are global by default. As the comment stated, you can use local to mark the variable as local to the function.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! And about that return value, is there some method? Something with similar to var=$(fun)
It's a bit odd. You can print the result and then capture the result into a variable: $ func() { local x; x="fred"; echo $x; }; $ wilma=$(func); $ echo $wilma which prints "fred"
Or, you can return an integer as an error code: $ func() { return 42 }; func; ERR=$?; echo $ERR which will print 42. (Note there has to be a newline between the return statement and the '}', which I can't include in a comment.
Thank you for answers :) It helped

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.