Bash - Variables

Learn how to declare and use variables in bash scripts. Types of global, local, and readonly variables, and understand proper syntax for accessing variables in shell scripts..

This post is about how to bash commands and programming tutorials with examples.

Bash Shell Variable

Variables form the fundamental building blocks of any programming language. Shell and bash script programming offer variables, much like other languages.

A variable serves as a container used for storing data in programming. It includes a pointer to the memory location of the data.

Declare variable : To create a variable, you must assign a value to it.

variableName :

It is the name of the variable, which can contain any combination of alphabets (a to z, A to Z), numbers (0 to 9), and underscores (_).

VariableValue is the value stored in a variable, and it can be a string of numbers or a boolean. The equal symbol (=) is used to assign a value to a variable.

For example

A variable named AGE is created and assigned the value 25.

How to Access Variables in Bash

After declaring and assigning values to variables, you can access them using a dollar symbol ( $ ) followed by the variable name.

This above code declares a variable named AGE with a value of 25 and then uses echo to display the value of the AGE variable. The dollar symbol before the variable name is crucial for accessing its value.

Bash Shell Readonly Variables

Once variables are assigned values, you can change them to new values using the assignment operator =.

How do you make variables not updatable?

The readonly keyword prevents a variable from being updated, effectively turning it into a constant .

AGE is an constaints, assigning new value throws an error , and the error message is AGE: is read-only .

Bash unset variable

The unset keyword assists in removing the value from the specified variable. The variable remains accessible but prints an empty value.

Above code,

  • first sets the variable AGE to 25, prints its value,
  • then unsets it using unset AGE.
  • Subsequently, it prints “empty” followed by the value of AGE, which now appears as empty space.

Variable Scopes

Every declared variable must have a scope, defining where in the program the variable can be used.

For instance, if a variable is declared within a function, it is available only within that function and is not accessible outside of it.

Variable scopes in Bash can be defined in two ways

  • Global variable
  • Local variable

Bash Global Variables

Variables declared in a shell script are referred to as global variables.

Global variables can be accessed within a function or any nested blocks of a shell script file.

The default variable declared in a script file is called a global variable.

Bash Local variables

Local variables are declared inside a block of code or a function. The scope of these variables is visible only within the block where they are declared.

In this syntax, the variable is declared and assigned with the local keyword.

A local variable is declared inside a function and is only visible within that function. Variables declared outside functions are called global variables and are available for all functions.

Variables typing

Bash scripting is not typed language, however you can declare an variable with a type of the data using declare command Based on the type of variable, it allows the type of the data .

variable is declared and assigned with a value.

Options contains option to create a type of a varialbe

Array: To create an array variable

declare -a variable=

Display Environment variables in Bash

In Bash, there are two types of commands for printing environment variables.

  • The printenv command
  • The env command

Both of these commands list all the environment variables of the terminal.

Variable nameing convention

  • Variables are read by prefixing with the $ symbol.
  • Variable names are composed of alphabets, numbers, or underscores.
  • Variables are case-sensitive; for example, test and Test are considered two different variables in scripting.
  • While variable names are conventionally written in UPPERCASE, you can create them using UPPER or LOWER case if needed. And Environment and Shell variables are both in UPPERCASE.
  • Variable names can not contain spaces
  • Names conventinaly should be camelCase. Example firstName

Bash Variable Tutorial – 6 Practical Bash Global and Local Variable Examples

bash assign global variable

Bash variables provide temporary storage for information that will be needed during the lifespan of the program. Syntax:

Note: There should not be any space around “=” sign in variable assignment. When you use VAR=VALUE, shell sees the “=” as a symbol and treats the command as a variable assignment. When you use VAR = VALUE, shell assumes that VAR must be the name of a command and tries to execute it.

Shell does not care about the type of variables. Variables could store strings, integers, or real numbers.

Example.1 Simple Bash Variable Assignment Usage

The following script creates a variable called LIST and assigns the value “/var/opt/bin”. To access the variables, just prefix the variable name with $, which will give you the value stored in that variable.

Execute the above script, which will list the /var/opt/bin in long format as shown below.

Bash Variable Scope – Local and Global

In Bash, variables do not have to be declared. But, when you access the variable which is not used so far, you will not get any warning or error message. Instead, it will display a blank value.

Example 2. Blank values in bash variables

As shown above, initially the variable will have a blank value, after assigning, you can get your values. export command is used to export a variables from an interactive shell. export shows the effect on the scope of variables.

Example 3. Bash Variables without export

Assign a variable with a value in an interactive shell, and try to access the same in your shell script.

Now, execute the above script as shown below.

Still you will get blank value for variable VAR2. The shell stores variable VAR2 with the LINUX only in the current shell. During the execution of var2.sh, it spawns the shell and it executes the script. So the variable VAR2 will not have the value in the spawned shell. You need to export the variable for it to be inherited by another program – including a shell script, as shown below.

Example 4. Exporting a Bash Variable

Now execute the above script.

Now, you can notice that after execution of the shell script var2.sh, the value of VAR2 is LINUX. Because the variables will not be passed back to your interactive shell, unless you execute the script in the current shell.

Declaring a Bash Variable

Using declare statement in bash, we can limit the value assigned to the variables. It restricts the properties of variables. Option in a declare statement is used to determine the type of a variable.

  • declare is a keyword
  • -r read only variable
  • -i integer variable
  • -a array variable
  • -f for funtions
  • -x declares and export to subsequent commands via the environment.

Example 5. Declaration of Bash variable using declare

From the below execution, you can notice the error message when you assign invalid data to a variable.

Global Bash Variables

Global variables are also called as environment variables, which will be available to all shells. printenv command is used to display all the environment variables.

Local Bash Variables

Local variables are visible only within the block of code. local is a keyword which is used to declare the local variables. In a function, a local variable has meaning only within that function block.

Example 6. Global and Local Bash Variables

Execute the above script,

In the above output, local variables will have only empty value before and after calling the function. Its scope is only with in the function. It got vanished out of the function, whereas the global variable has the updated value even after the function execution.

If you enjoyed this article, you might also like..

Tagged as: Bash Tutorial , Bash Variable Export , printenv , Unix Export Command

Comments on this entry are closed.

Can you elaborate on this piece of code:

var=$(cat file.txt)

How do i convert the above to an indexed array, list…?

Under Declaring a Bash Variable”, you can add -A. Bash version 4 introduced associative arrays.

Have you seen anything to be gained, performance wise, when declaring a string that requires no substitution with single quotes vs double quotes.

LIST=’/var/opt/bin/’ vs. LIST=”/var/opt/bin/”

Not at all, but i prefer cat command or l 🙂 By the way we are using bash 3 🙁 so it is not possible, to use the -A array, i am not the admin either

Can you elaborate on this piece of code: var=$(cat file.txt) How do i convert the above to an indexed array, list…?

The above reference is command substitution; it functions like using back ticks IE: `cat file.txt`.

So the out put of the command is stored in the variable var.

If you echo $var it will be one long line If you echo “$var” it will appear as it does in the text file.

You can think of it as a one line array. Array’s can have an index or may not be indexed at all. You can still loop through each element. Might depend on the version of bash if it needs to be quoted or not. I forget how 2.x and 3.x worked… Sorry I am on version 4.x…

If you want an index; you have to create a counter variable. As each line is read; you increment that counter. There are various ways to populate an (indexed) array. You can use the read command, process substitution and back ticks with a variable.

Check out the BASH guides at the TLDP for various ways to populate an array.

Thanks for writing this article. Couldn’t find much good newbie level material on bash variables but this really helped me out.

Next post: Bg, Fg, &, Ctrl-Z – 5 Examples to Manage Unix Background Jobs

Previous post: How To Fix Offending key in ~/.ssh/known_hosts file

Linux 101 Hacks Book

  • Bash 101 Hacks eBook - Take Control of Your Bash Command Line and Shell Scripting
  • Sed and Awk 101 Hacks eBook - Enhance Your UNIX / Linux Life with Sed and Awk
  • Vim 101 Hacks eBook - Practical Examples for Becoming Fast and Productive in Vim Editor
  • Nagios Core 3 eBook - Monitor Everything, Be Proactive, and Sleep Well

POPULAR POSTS

  • 15 Essential Accessories for Your Nikon or Canon DSLR Camera
  • 12 Amazing and Essential Linux Books To Enrich Your Brain and Library
  • 50 UNIX / Linux Sysadmin Tutorials
  • 50 Most Frequently Used UNIX / Linux Commands (With Examples)
  • How To Be Productive and Get Things Done Using GTD
  • 30 Things To Do When you are Bored and have a Computer
  • Linux Directory Structure (File System Structure) Explained with Examples
  • Linux Crontab: 15 Awesome Cron Job Examples
  • Get a Grip on the Grep! – 15 Practical Grep Command Examples
  • Unix LS Command: 15 Practical Examples
  • 15 Examples To Master Linux Command Line History
  • Top 10 Open Source Bug Tracking System
  • Vi and Vim Macro Tutorial: How To Record and Play
  • Mommy, I found it! -- 15 Practical Linux Find Command Examples
  • 15 Awesome Gmail Tips and Tricks
  • 15 Awesome Google Search Tips and Tricks
  • RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
  • Can You Top This? 15 Practical Linux Top Command Examples
  • Top 5 Best System Monitoring Tools
  • Top 5 Best Linux OS Distributions
  • How To Monitor Remote Linux Host using Nagios 3.0
  • Awk Introduction Tutorial – 7 Awk Print Examples
  • How to Backup Linux? 15 rsync Command Examples
  • The Ultimate Wget Download Guide With 15 Awesome Examples
  • Top 5 Best Linux Text Editors
  • Packet Analyzer: 15 TCPDUMP Command Examples
  • The Ultimate Bash Array Tutorial with 15 Examples
  • 3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
  • Unix Sed Tutorial: Advanced Sed Substitution Examples
  • UNIX / Linux: 10 Netstat Command Examples
  • The Ultimate Guide for Creating Strong Passwords
  • 6 Steps to Secure Your Home Wireless Network
  • Turbocharge PuTTY with 12 Powerful Add-Ons
  • Linux Tutorials
  • Sed Scripting
  • Awk Scripting
  • Bash Shell Scripting
  • Nagios Monitoring
  • IPTables Firewall
  • Apache Web Server
  • MySQL Database
  • Perl Programming
  • Google Tutorials
  • Ubuntu Tutorials
  • PostgreSQL DB
  • Hello World Examples
  • C Programming
  • C++ Programming
  • DELL Server Tutorials
  • Oracle Database
  • VMware Tutorials

About The Geek Stuff

Copyright © 2008–2023 Ramesh Natarajan. All rights reserved | Terms of Service

TecAdmin

Bash LOCAL and GLOBAL Variables

In programming languages, variables are named containers that store values. They are the backbone of any program, allowing us to create dynamic scripts. In Bash scripting, we have two main types of variables – Global and Local . This article will offer a deep dive into these types, showing you how to declare, use, and manipulate them.

Introduction to Bash Variables

In Bash (Bourne Again SHell), a shell for the GNU operating system, variables are utilized to store data. Their names are case-sensitive and traditionally are capitalized, although lower case names are also allowed.

To assign a value to a variable, we use the equals sign ( = ) with no spaces around it. For instance:

This assigns the string “TecAdmin” to the variable `NAME` .

Once a variable is assigned, we can access its value using a dollar sign ( $ ). The following command will print the variable `NAME` to the console:

Global Variables

By default, every variable we create in Bash is global. This means it’s accessible anywhere in the script, regardless of scope. They can be used in any function, loop, or conditional statement within the script.

In the script above, `GLOBAL_VAR` is a global variable, and it’s accessible within the function test.

Local Variables

Unlike global variables, local variables are confined to the block of code or function in which they are declared. Outside of that block, the variable is not recognized.

We create a local variable in Bash by using the `local` keyword.

Here’s an example:

In this script, `LOCAL_VAR` is defined within the function test. When we try to echo LOCAL_VAR outside of the function, it returns nothing since it’s not recognized outside of its local scope.

Interaction between Local and Global Variables

Let’s understand what happens when we use a local variable with the same name as a global variable.

In this script, the function test declares a local variable `VAR` that shares the same name as a global variable. Within the function, the local variable takes precedence over the global one, but outside the function, the global variable maintains its value. This concept is called ‘variable shadowing’ .

Understanding variable scopes and how to work with local and global variables is fundamental to scripting in Bash. It allows us to control where variables can be accessed and modified, providing a layer of security to our scripts. Global variables are accessible anywhere in the script, whereas local variables can only be used in the block of code or function where they’re declared. Always remember to use the most restrictive scope possible for your variables to avoid unexpected behavior in your scripts.

Related Posts

Single-line if-else statements in bash, (resolved) “-bash: ping: command not found” error in docker.

Bash Generate Random Numbers

Generate Random Numbers in Bash

Leave a reply cancel reply.

Save my name, email, and website in this browser for the next time I comment.

Type above and press Enter to search. Press Esc to cancel.

Bash Variables Explained: A Simple Guide With Examples

Master Bash variables with the help of these explanations and examples.

Variables are used for storing values of different types during program execution. There are two types of variables in Bash scripting: global and local.

Global variables can be used by all Bash scripts on your system, while local variables can only be used within the script (or shell) in which they're defined.

Global variables are generally provided on the system by default and are mainly environment and configuration variables. Local variables, on the other hand, are user-defined and have arbitrary uses.

Bash Local Variables

To create a variable, you need to assign a value to your variable name. Bash is an untyped language, so you don't have to indicate a data type when defining your variables.

Bash also allows multiple assignments on a single line:

Just like many other programming languages, Bash uses the assignment operator = to assign values to variables. It's important to note that there shouldn't be any spaces on either side of the assignment operator. Otherwise, you'll get a compilation error.

Related: What Does "Bash" Mean in Linux?

Another key point to note: Bash doesn't allow you to define a variable first and then assign a value to it later. You must assign a value to the variable at creation.

Sometimes, you may need to assign a string that has a space in it to your variable. In such a case, enclose the string in quotes.

Notice the use of single quotes. These quotes are also called "strong quotes" because they assign the value precisely as it's written without regard to any special characters.

In the example above, you could have also used double quotes ("weak quotes"), though this doesn't mean they can always be used interchangeably. This is because double quotes will substitute special characters (such as those with $ ), instead of interpreting them literally.

See the example below:

If you want to assign a command-line output to your variable, use backquotes ( `` ). They'll treat the string enclosed in them as a terminal command and return its result.

Parameter Expansion in Bash

Parameter Expansion simply refers to accessing the value of a variable. In its simplest form, it uses the special character $ followed by the variable name (with no spaces in between):

You can also use the syntax ${variableName} to access a variable's value. This form is more suitable when confusion surrounding the variable name may arise.

If you leave out the curly brackets, ${m}ical will be interpreted as a compound variable (that doesn't exist). This use of curly brackets with variables is known as "substitution".

Global Variables

As mentioned earlier, your Linux system has some built-in variables that can be accessed across all of your scripts (or shells). These variables are accessed using the same syntax as local variables.

Related: How to Create and Execute Bash Scripts in Linux

Most of these variables are in BLOCK letters. However, some are single characters that aren't even alphanumeric characters.

Here are some common useful global variables:

HOME : Provides the user's home directory

SHELL : Provides the type of shell you're using (e.g Bash, csh..etc)

? : Provides the exit status of the previous command

To get a list of global variables on your system, run the printenv (or env) command:

Loops in Bash Scripting

Now you know what variables are, how to assign them, and how to perform basic Bash logic using them.

Loops enable you to iterate through multiple statements. Bash accommodates for loops and while loops with a simple syntax for all of your looping needs.

If you're mastering the art of Bash development, for loops ought to be next up on your list.

LinuxOPsys

How to Assign Variable in Bash

  • Bash Scripting

bash variable-assignment

A variable is a named storage location in a program's memory where a value can be stored, retrieved, and manipulated. Like any programming language, Variables are an essential component in the Bash scripts. They allow you to create dynamic scripts that can change based on the data that is passed to them.

In Bash, there are different ways to assign variables which will be covered in detail.

Local vs Global variable assignment

Bash has two types of variables - local, and global based on the scope where they are defined in the script.

Local variable

A local variable is a variable that is defined within a function or a block of code and can only be accessed within that function or block. Local variables are only accessible within the function or block in which they are defined and the value of the variable is lost once the function or the block ends.

Global variable

A global variable, on the other hand, is a variable that is defined outside of any function or block and can be accessed from any part of the program. Global variables are accessible from anywhere in the program, including from within functions and blocks.

See the following script to understand the scope and lifetime of local vs global variables:

In the script:

  • num=2 initializes the global num variable.
  • local num=1 declared inside the function demo_local_va r block initializes the local num variable whose scope is within the function only
  • Outside this function, echoing $num always prints the value of global num variable.

Local vs Global variable

Single variable assignment

In bash, a single variable can be assigned simply using the syntax

with no space before and after the `=` sign. You do not need to declare the data type in bash while assigning a variable.

Integer assignment

To assign an integer to a variable, you can use the following syntax:

In the script, num=1 assigns a global integer variable value 1.

integer variable assignment

String assignment

There are multiple ways to assign strings:

  • Single words can be assigned directly without any quotes.
  • Multi-word strings can be defined using Single quotes (') and Double quotes (").

However, there is a difference between how Bash interprets single quotes and double quotes.

When you use single quotes to define a string, it preserves the literal value of each character. On the other hand, if you use double quotes, it recognizes the special symbols ($, `, \) and expands the strings using the shell expansion rules.

In this example,

  • greeting2 treats $name as a string and thus it gets expanded to Hello $name .
  • While greeting3 expands $name to world , thus generating the string - Hello world .

string variable assignment

Boolean assignment

To assign a boolean value to a variable, you can use the following syntax:

  • true_val=true and false_val=false initializes the boolean variables.
  • We can use these booleans in conditional statements to make decisions.

boolean variable assignment

Multi-variable assignments

Bash provides a straightforward syntax for assigning multiple variables in a single line as follows:

multiple variable assignment

In the above script, a=1, b=2, c=3 initializes three integer variables using a single statement.

Default value assignment

Bash has a built-in syntax for providing default values to the variables:-

If var is not defined, it assigns the defaultval to the newVar.

See the following script to see how default assignments work:

  • In the first example, echo $userOutput1 prints 5 to the stdout since var1 is defined.
  • In the second example, echo $userOutput2 prints var2 is not defined since var2 is not defined before.

assign default value to the variable

Using let command for assignments

The let command is used to assign numeric values to the variables and perform arithmetic, bitwise, and logical operations.

Consider the following script:

assign numeric values to the variables using let

let command is an important utility which provides a simplistic syntax to perform a variety of arithmetic, logical and bitwise operations.

Using Read command

Bash has a built-in read command that can read a line from the standard input (stdin) and split the line into multiple variables.

See the following script to understand how the read command works:

read into multiple variables

In the script read animal color accepts 2 inputs from the user and stores them in the variables animal and color .

Read command also comes with some useful options:

Prompt flag (-p) helps to provide a useful text to the user and accept inputs. This removes the additional need for echo statements simplifying the code.

Silent flag (-s) helps the user to hide the input from display. This is useful when entering sensitive information such as passwords.

  • Input to array

Array (-a) flag reads the input to an array instead of individual words.

  • read -p “Enter the username: “   prints the text “Enter the username: “ and also accepts an input from the user.
  • read -s -p “Enter the password: “   accepts an input from the user in silent mode, i.e. it is not displayed on the screen.
  • read -p “Enter your hobbies(space separated): “ -a hobbies accepts an array input from the user into hobbies variable. The variable can then be iterated over using the array iteration syntax.

bash assign global variable

  • Bash supports both local and global variables. Using global variables, in general should be avoided since they increase the complexity of the code and may introduce hard to debug bugs.
  • Bash provides built-in support for assigning integer, strings and boolean type variables. Data type is not required while assigning variables.
  • Multiple variables can be assigned simply by defining multiple variables in a single line.
  • Bash also supports initializing variables with default values. This is a good programming practice and helps to avoid bugs due to uninitialized variables.
  • The let command is a useful built-in in bash for working with numerics and performing a variety of operations.
  • The read command is another important built-in to read input from the command line and create interactive applications.

If this resource helped you, let us know your care by a Thanks Tweet. Tweet a thanks

Like

Sorry about that.

About The Author

Madhur batra.

Madhur Batra

Madhur Batra is a highly skilled software engineer with 8 years of personal programming experience and 4 years of professional industry experience. He holds a B.E. degree in Information Technology from NSUT, Delhi. Madhur's expertise lies in C/C++, Python, Golang, Shell scripting, Azure, systems programming, and computer networking. With a strong background in these areas, he is well-equipped to tackle complex software development projects and contribute effectively to any team.

What is Shell in Linux

Check Which Shell You are Using on Linux

Script to Check Linux Server Health

Types of Shells in Linux

Pass all Arguments in Bash Scripting

Concatenate String Variables in Bash [Join Strings]

How to Do Bash Variable Substitution

Bash Parameter Expansion with Cheat Sheet

Create Multiline Strings in Bash

Bash Division Explained

Bash Loop Through Lines in a File

How to Use While Loop in Bash

Bash for Loop Range Variable

Bash If Else Statements: Examples and Syntax

How to Read CSV File in Bash

Leave a Reply

Leave a comment cancel reply.

How-To Geek

Bash functions and local variables.

This article will demonstrate how local variables functions are used and created in Bash.

Quick Links

  • What Are Bash Functions?

Simple Bash Function

Passing variables to bash functions, local variables and returning values, wrapping up.

This article will demonstrate how local variables functions are used and created in Bash. Creating Bash functions allows you to make your code more structural, and local variables help with security and avoiding coding mistakes. Dive in!

What Are Bash Functions ?

Alike to other coding languages, Bash allows you to create functions from within your code or script. A function can be defined to do a specific task, or set of tasks, and can be called easily and readily from within your main code by simply using the name given to the function.

You can also nest function calls (calling a function from within another function), use local variables within the function and even pass variables back and forth with functions, or via using global variables. Let's explore.

We define a test.sh with our text editor, as follows:

#!/bin/bash

echo "welcome"

Subsequently, we make that file executable by adding the execute ( x ) property, and execute the script:

chmod +x test.sh

A simple Bash function

We can see how the script first defines a welcome() function using the Bash idioms function_name() , and { ... } function wrappers. Finally, we call the function welcome by simply using it's name, welcome .

When the script is executed, what happens in the background, is that the function definition is noted, but skipped (i.e. not executed), until a bit lower the function call welcome is hit, and which point the Bash interpreter executes the welcome function and returns to the line directly after the function calls afterwards, which in this case is the end of our script.

We define a test2.sh with our favorite text editor (vi ;), as follows:

if [ -z "${1}" ]; then

echo "One option required!"

echo "${1}"

echo "${2} ${1}"

func1 "${1}"

func2 "a" "b"

We again make our script executable by using chmod +x test2.sh and execute the same.

A more advanced Bash function with variable passing

The resulting output may look interesting, or even confusing at first. However, it is logical and easy to follow. The fist option passed to the script will, globally, be available from within the code as ${1} , except inside functions, where ${1} becomes the first parameter passed to the function, ${2} the second etc.

In other words, the global ${1} variable (the first option passed to the script from the command line) is not available from within functions, where the meaning of the ${1} variable changes to the first option passed to the function. Think hierarchy, or think about how a function could present a small script by itself and this will soon make sense.

As a sidenote, one could also use $1 instead of ${1} , but I strongly encourage aspiring Bash coders to always surround variable names with { and } .

The reason is that sometimes, when using variables in a string for example, the Bash interpreter is not able to see where a variable ends and part of the adjoining text may be taken to be part of the variable name where it is not, leading to unexpected output. It is also cleaner and clearer what the intention is, especially when it comes to arrays and special option flags.

We thus start our program with the global ${1} variable set to "first" . If you look at the calling of func1 , you will see that we pass that variable onto the function, thus the ${1} inside the function becomes whatever was in the ${1} of the program, i.e. "first" , and this why the first line of output is indeed first .

We then call func2 and we pass two strings "a" and "b" to the function. These then become the ${1} and ${2} automatically inside the func2 function. Inside the function, we print them in reverse, and our output matches nicely with b a as the second line of output.

Finally, we also do a check at the top of our script which ensures that an option is actually passed to the test2.sh script by checking if "${1}" is empty or not using the -z test inside the if command. We exit the script with a non-zero exit code ( exit 1 ) to indicate to any calling programs that something went amiss.

For our final example, we define a test3.sh script as follows:

local REVERSE="$(echo "${1}" | rev)"

echo "${REVERSE}"

INPUT="abc"

REVERSE="$(func3 "${INPUT}")"

We again make it executable and execute the script. The output is cba as can be expected by scanning over the code and noting the variable names etc.

However, the code is complex and takes a little getting used to. Let's explore.

First, we define a function func3 in which we create a local variable named REVERSE . We assign a value to it by calling a subshell ( $() ), and from within this subshell we echo whatever was passed to the function ( ${1} ) and pipe this output to the rev command.

The rev command prints the input received from the pipe (or otherwise) in reverse. Also interesting to note here is that the ${1} variable remains inside the subshell! It is past integrally.

Next, still from within the func3 function, we print the output. However, this output will not be sent to the screen, it rather will be captured by our function call itself and thus stored within the 'global' REVERSE variable.

We set our input to "abc" , call the func3 function again from within a subshell, passing the INPUT variable, and assign the output to the REVERSE variable. Note that there is absolutely no connection between the 'global' REVERSE variable and the local REVERSE variable inside the script.

Whilst any global variable, including any REVERSE will be passed to the function, as soon as a local variable is defined with the same name, the local variable will be used. We can also prove and see this another small script test4.sh:

REVERSE="test"

func3 "${INPUT}"

Bash function and local variable example exemplifying two of the learning points seen so far

When executed the output is cba and test . The cba is this time generated by the same echo "${REVERSE}" inside the func3 function, but is this time output directly instead of captured in the code below as the func3 "${INPUT}" function is not called from within a subshell.

This script highlights two learning points we covered earlier: firstly, that - even though we set the REVERSE variable to "test" inside the script before calling the func3 function - that the local variable REVERSE takes over and is used instead of the 'global' one.

Secondly, that our 'global' REVERSE variable retains it value even though there was a local variable with he same name used from within the called function func3 .

As you can see, Bash functions, the passing of variables, as well as the use of local and semi-global variables makes the Bash scripting language versatile, easy to code, and gives you the possibility to define well structured code.

Also noteworthy to mention here is that besides improved code readability and easy-of-use, using local variables provides additional security as variables will not be accessible outside of the context of a function etc. Enjoy functions and local variables whilst coding in Bash!

If you're interested in learning more about Bash, checkout our How to Correctly Parse File Names in Bash , and Using xargs in Combination With bash -c to Create Complex Commands .

LinuxSimply

Home > Bash Scripting Tutorial > Bash Functions > How to Return Values From Function in Bash [6 Examples]

How to Return Values From Function in Bash [6 Examples]

Mitu Akter Mou

Return values are an integral part of a Bash function. The bash function returns values by using the return statement. There are some other techniques as well like using echo command or global variables. In this article, I will show 6 examples of how the bash function returns values such as integer, string, boolean, and array. Additionally, the importance of return values used in error handling will be addressed. I will also cover some pitfalls in returning values and their solutions for more robust bash scripting.

What is a Function in Bash?

Bash function is a set of commands grouped under a single name that is reusable and performs a specific task. To make a script more readable and organized, using the bash function is a good idea. It helps to avoid writing the same code or commands repeatedly. You can just call the function anywhere in the script to accomplish the desired task. The bash function uses return values to indicate the success or failure of the last executed command.

The syntax of a bash function is as follows:

function_name: This is the name you give to your function. It follows the same rules as variable names in Bash. Also, you can use the function keyword before the function name to create a function.

(): These parentheses indicate the start and end of the function parameter list. You can omit the parentheses if your function doesn’t take any parameters.

# Commands or code blocks: This is the function body where the commands or code blocks are placed to execute the function.

{}: These curly braces contain the body of the function.

What are Return Values in Bash Function?

Returns values are the values that a bash function returns through the exit status when the function is completed. The exit status captures the return value of the bash function which is stored in a special variable $? . A return statement can be used to return an integer value between 0 and 255. Here, 0 indicates success and a non-zero value indicates failure of the last executed command. To return other values like string or array, using echo command or global variables is a great way.

6 Examples of Return Values From Bash Function

In this section, how the bash function returns one value or multiple is discussed. Additionally, the bash function can return values as strings or arrays using echo command or global variables. Most importantly, these return values can be used in handling errors. Let’s delve into the details.

1. Return One Value as Integer

To return one integer value between 0 to 255 from the bash function, use the return statement. This statement ends the function by returning the exit status to the caller function. The exit status is the return value of the bash function. Follow the script to see how it works:

First, a Bash function is defined named multiply_numbers that takes two parameters (num1 and num2), calculates their product (multiplication), and returns the result as the exit status. The local keyword is used to make the variable local to the function. multiply_numbers 5 3 calls the function with arguments 5 and 3, and the exit status of the function is captured in the variable “result” using $? . echo "Multiplication result: $result" prints the multiplication result obtained from the exit status of the function.

returning values as integer in bash

As you can see, the bash function returns 15 and prints it in the terminal. However, this script cannot return a value more than 255. To avoid this issue, follow the Exceeding Return Value Limit section.

2. Return Multiple Values

Multiple values can be returned from the bash function using a Bash array . For that, define a function and then create an array that includes the values that will be returned from the function using the echo command. Here’s how:

The script defines a function multiple_values that creates an array with three values (“Ubuntu”, “Linux”, and “Red-hat”). echo "${array[@]}" prints the elements of the array separated by spaces. Then the function multiple_values is called, and its output is captured in the result array. The $(...) syntax is used to execute the function and capture its output as an array. Finally, the script prints the individual values from the result array using array indexing (${result[0]}, ${result[1]}, and ${result[2]}) .

return multiple values from bash function

This image demonstrates multiple values returned from a Bash function using an array.

3. Return Value as String

Like other programming languages, Bash does not support returning string values directly from the bash function. So to return the value as the string, use the echo command with the command substitution method. Follow the script to learn how to return string value from the function:

Here, the Bash function named “greetings” takes a parameter “name”, echoes a greeting using the provided name, and then echoes a “Good Morning” message. message=$(greetings "John") calls the “greetings” function with the argument “John”. The output of the function (both lines of greeting) is captured in the variable “message” using command substitution ($(...)) .

returning string from bash function

Upon executing the script, it displays the greeting message of the bash function.

4. Return Value as Boolean

There is no boolean type in the Bash function, but the exit status of a command can be used to represent a boolean value. Usually, a command with a successful execution returns an exit status of 0 (which is considered true ), whereas a non-zero exit status is considered false . Here’s an example of a Bash function that returns a boolean value based on the file’s existence:

This script checks if a file exists or not by creating a bash function named “file_exists”. The function takes one parameter, file_path , and checks if the file specified by file_path exists using the -f test in a conditional expression. If the file exists, the function returns 0 (true) and prints “File exists!”. If it doesn’t exist, it returns 1 (false) and echoes “File not found.”.

checking file existence using bash return value as boolean

Since “file.txt” is in the system, it shows “File exists”.

5. Return Values (Array) Using Global Variable

A global variable in bash is a variable declared outside of a function. It can be accessed and changed both inside and outside of the function. Because of this, there is a high chance of an unexpected error. Therefore, it is recommended to use local variables.

Now, see how the values are returned from the Bash function using a global variable:

declare -a numbers_array declares a global array variable named numbers_array . The -a flag indicates that it’s an indexed array . The get_numbers function is created to assign values (1, 2, 3) to the global array variable. After calling the function, it prints the elements of the global array using ${numbers_array[@]} .

return values using global variables

As you can see, the values of the global array are shown in the terminal.

6. Return Values in Error Handling

Return values can be used to gracefully handle errors in the Bash function. In this example, the exit status is checked before performing the division operation using the $? variable. If the denominator is 0, the script will show an error message. Here’s the complete bash script for this:

The division function takes two parameters numerator and denominator. Before performing the division, it checks if the denominator is 0 or not. If the divisor is 0, the function prints an error message and returns a non-zero value to indicate failure. When the division is successful, the function prints the result and returns 0 to indicate success.

local result=$((numerator / denominator)) performs the division of the numerator by the denominator and stores the result in the result variable. division 10 0 calls the division function with arguments 10 and 0. The condition $? -eq 0 within the if statement checks the exit status of the last executed command. If the exit status is 0,  it prints “Division successful”; otherwise, prints “Error in division”.

return values in error handling

Since the denominator is 0, it displays an error message.

Common Issues with Bash Return Values

There are some problems that you may encounter while working with the bash function to return values. Let’s take a look at these problems and how to solve them.

Exceeding Return Value Limit

The return statement returns integer values between 0 and 255. Exceeding this range shows an unexpected result:

exceeding limit error

Here the value 9 is the remainder of 265 divided by 256. Actually, it resets to 0 after crossing the range. As an example, it yields 0 for 256, 1 for 257, and so forth. Likewise, it displays 9 for 265.

To avoid this problem and get the actual output, use the echo command or global variables:

The echo command with command substitution returns the value 265 as expected:

solution of exceeding limit error

Not Capturing Return Value

$? is used to capture the return value of the return statement. This must be used immediately after calling the function. If another command is called before the return value is captured, $? will be overwritten like this:

not capturing return value error

To solve this issue, write the $? immediately after the function has been called to capture the return value properly:

solution of not capturing return value error

As you can see in the image the actual return value 25 is displayed on the terminal.

Uninitialized Variable Error

If a variable is not initialized in the function, it can lead to an error:

unset variable value error

Since the local variable value is unset in the function, it displays the empty result. To solve this problem, initialize the variable value first:

solution of unset variable value error

Once the variable value has been set to 10, it will display the actual result.

Practice Tasks on Return Values from Bash Function

To improve your bash scripting skills and to understand how to return values from the bash function, practice the following:

  • Write a Bash script that defines a function add_numbers which takes two parameters, adds them, and returns the integer result.
  • Create a Bash script that defines a function is_even that takes a number as a parameter, and checks if it is even or odd.
  • Make a script where a function named reverse_string takes a string as a parameter, reverses it, and returns the reversed string.
  • Generate a script and create a function fibonacci that takes a number “n” as a parameter and returns the nth value in the Fibonacci sequence.

To conclude, I have covered the fundamentals of the bash function and how it returns values. Moreover, I have provided 6 examples of how to return values like integer, string, and array from the bash function. Some problems associated with returning values and their solutions are also explained. Lastly, don’t forget to complete the practice tasks. Have a great day!

People Also Ask

What is the return type and return value.

The return value is the value that a function produces when it finishes its execution. It is basically the result of the function and the data type of the return value is called the return type.

Do all functions return a value?

No. All functions don’t return a value. Whether a function returns value or not depends on the purposes of the function.

Can you call a void function?

Yes , you can call a void function. The void function is a function that does not return a value. So no return statement is required. At the end of a void function, it automatically returns to the caller.

Can a function only return once?

Actually, a function may have more than one return statement, but it returns a value the very first time it comes into contact with the return statement. When the function receives a return statement, it immediately exits and no more code is executed in the function. To execute multiple returns, you can use other approaches like using an array.

Can a function repeat itself?

Yes, a function in Bash can repeat itself using loops or recursive calls. Both for and while loops can be used for repeating a task within a function. Functions can also recursively call themselves.

Can functions return two values?

Yes, a function can return two values using a bash array and echo command. Here’s the example bash script:

Modify the code by replacing the values you want to return.

Mitu Akter Mou

Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

IMAGES

  1. Bash Script: define las variables Bash y sus tipos

    bash assign global variable

  2. Bash Function & How to Use It {Variables, Arguments, Return}

    bash assign global variable

  3. How to use Variables in Bash

    bash assign global variable

  4. Bash LOCAL and GLOBAL Variables

    bash assign global variable

  5. How to use Variables in Bash

    bash assign global variable

  6. Bash Variable Tutorial

    bash assign global variable

VIDEO

  1. Create Global LMS and Assign to Batches

  2. How to Assign Courses to Users

  3. Section-5: Vidoe-10 : Command Line Arguments to provide inputs for Variables of Bash Shell Script

  4. Imp Points To Develop Real-Time Bash Shell Scripts

  5. Difference between local and global variable

  6. Bash scripting Tutorial for DevOps Engineers part 02

COMMENTS

  1. How to modify a global variable within a function in bash?

    How to modify a global variable within a function in bash? - Stack Overflow How to modify a global variable within a function in bash? Ask Question Asked 9 years, 9 months ago Modified 4 months ago Viewed 294k times 164 I'm working with this: GNU bash, version 4.1.2 (1)-release (x86_64-redhat-linux-gnu) I have a script like below:

  2. bash

    1 asked Sep 23, 2017 at 2:35 hellojoshhhy 205 1 3 7 Add a comment 3 Answers Sorted by: 18 var1 is declared local in the function. So during the execution of the function there are two variables named var1: the global one and the local one; but the function can only "see" the local one (the local one "shadows" the global one).

  3. A Total Guide on Global Variable in Bash [3 Examples]

    Flexible Global variables help the Bash scripts to adapt the required updates and configurations. These variables are so flexible that it's enough to modify them only from one place to implement the new changes inside the script. Store Configuration Settings

  4. Understanding Global, Local, and Readonly Variables in Bash Shell

    Declare variable : To create a variable, you must assign a value to it. variableName=VariableValue variableName: It is the name of the variable, which can contain any combination of alphabets (a to z, A to Z), numbers (0 to 9), and underscores (_). VariableValue is the value stored in a variable, and it can be a string of numbers or a boolean.

  5. Bash Variable Tutorial

    Bash Variables without export. Assign a variable with a value in an interactive shell, and try to access the same in your shell script. ... Global Bash Variables. Global variables are also called as environment variables, which will be available to all shells. printenv command is used to display all the environment variables.

  6. Bash LOCAL and GLOBAL Variables

    1 echo $NAME ADVERTISEMENT Global Variables By default, every variable we create in Bash is global. This means it's accessible anywhere in the script, regardless of scope. They can be used in any function, loop, or conditional statement within the script. 1 2 3 4 5 6 7 8 9 #!/bin/bash GLOBAL_VAR = "I am a global variable" function test {

  7. How to Work with Variables in Bash

    Here, we'll create five variables. The format is to type the name, the equals sign =, and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable. We'll create four string variables and one numeric variable, my_name=Dave.

  8. How to Assign Variable in Bash Script? [8 Practical Cases]

    In Bash scripting, global variables are accessible throughout the entire script, regardless of the scope in which they are declared. Global variables can be accessed and modified from any script part, including within functions. Here are some key characteristics of global variable assignment:

  9. linux

    setting global variable in bash Ask Question Asked 8 years, 9 months ago Modified 8 years, 9 months ago Viewed 34k times 8 I have function where I am expecting it to hang sometime. So I am setting one global variable and then reading it, if it didn't come up after few second I give up.

  10. Bash Variables Explained: A Simple Guide With Examples

    Global variables are generally provided on the system by default and are mainly environment and configuration variables. Local variables, on the other hand, are user-defined and have arbitrary uses. Bash Local Variables . To create a variable, you need to assign a value to your variable name. Bash is an untyped language, so you don't have to ...

  11. How to Assign Variable in Bash

    Bash supports both local and global variables. Using global variables, in general should be avoided since they increase the complexity of the code and may introduce hard to debug bugs. Bash provides built-in support for assigning integer, strings and boolean type variables. Data type is not required while assigning variables.

  12. Bash Variables

    Value Assigning in a Variable: Variables are assigned values using the '=' operator. No spaces should be present around the '=' sign. ... To use local and global variables in bash, follow the below script: #!/bin/bash #setting value to number variable number=10 #defining addition function function addition() { #defining number variable ...

  13. Bash Functions and Local Variables

    Wrapping Up. As you can see, Bash functions, the passing of variables, as well as the use of local and semi-global variables makes the Bash scripting language versatile, easy to code, and gives you the possibility to define well structured code. Also noteworthy to mention here is that besides improved code readability and easy-of-use, using ...

  14. Bash function assign value to passed parameter

    However, as far as I understand it, the function returns the result value by echo ing it or by assigning it to a global variable. I do want to echo to the screen in the function though, so it'll have to be option two. So i tried this:

  15. How to Use Variables in Bash Shell Scripts

    Using variables in bash shell scripts In the last tutorial in this series, you learned to write a hello world program in bash. #! /bin/bash echo 'Hello, World!' That was a simple Hello World script. Let's make it a better Hello World. Let's improve this script by using shell variables so that it greets users with their names.

  16. How to Return Values From Function in Bash [6 Examples]

    To return other values like string or array, using echo command or global variables is a great way. 6 Examples of Return Values From Bash Function. In this section, how the bash function returns one value or multiple is discussed. Additionally, the bash function can return values as strings or arrays using echo command or global variables. Most ...