Skip to Content
Mastering Linux Shell Scripting - Second Edition
book

Mastering Linux Shell Scripting - Second Edition

by Mokhtar Ebrahim, Andrew Mallett
April 2018
Beginner
284 pages
7h 3m
English
Packt Publishing
Content preview from Mastering Linux Shell Scripting - Second Edition

Variable scope

By default, any variable you declare inside a function is a global variable. That means this variable can be used outside and inside the function without problems.

Check out this example:

#!/bin/bash 
myvar=10 
myfunc() { 
   myvar=50 
} 
myfunc 
echo $myvar 
 

If you run this script, it will return 50, which is the value changed inside the function.

What if you want to declare a variable that is exclusive to the function? This is called a local variable.

You can declare local variables by using the local command like this:

myfunc() { 
   local myvar=10 
} 

To ensure that the variable is used only inside the function, let's check out the following example:

#!/bin/bash 
myvar=30 
myfunc() { 
   local myvar=10 
} 
myfunc 
echo $myvar 

If you run this ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Linux Shell Scripting - Second Edition

Learning Linux Shell Scripting - Second Edition

Ganesh Sanjiv Naik
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781788990554Supplemental Content