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!

SevO
  • 303
  • 2
  • 11
  • local/declare are the options to investigate – grail Mar 18 '17 at 08:13
  • The answer to most basic bash questions can be found in the manual: https://tiswww.case.edu/php/chet/bash/bashref.html – ccarton Mar 18 '17 at 11:35
  • 4
    Possible duplicate of [Bash variable scope](https://stackoverflow.com/q/124167/608639), [Defining common variables across multiple scripts?](https://stackoverflow.com/q/27226650/608639), [How to export a variable in bash](https://stackoverflow.com/q/307120/608639), [How do I define a shell script variable to have scope outside of the script](https://stackoverflow.com/q/8153923/608639), etc. – jww May 10 '18 at 02:36

1 Answers1

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.

A. L. Flanagan
  • 1,162
  • 8
  • 22
  • Thank you! And about that return value, is there some method? Something with similar to `var=$(fun)` – SevO Mar 18 '17 at 01:09
  • 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" – A. L. Flanagan Mar 18 '17 at 01:15
  • 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. – A. L. Flanagan Mar 18 '17 at 01:21
  • Thank you for answers :) It helped – SevO Mar 18 '17 at 01:30