How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (2023)

Lal»Bash scripting tutorial»bash variables»Variable declaration and assignment»How to assign variables in Bash script? [8 actual cases]

script bash

Muhammad Xia Milan

August 2, 2023

variables allow you toshopemanipulateData in scripts to facilitate organization and access to information. existscript bash, variable assignment follows a simple syntax, but offers a variety of options and features that enhance the flexibility and power of your scripts. In this article, I will discussWays to assign variables in Bash scripts. Since Bash scripting offers several ways to assign variables, I'll dive into each of them.

index expansion

main conclusion

  • Become familiar with the different types of variables.
  • Learn how to assign single or multiple bash variables.
  • Learn about arithmetic operations in Bash scripting.

free download

Download exercise files

Local variable assignment vs. global variable assignment

In programming, variables are used to store and manipulate data. There are two main types of variable assignments:LocaleGlobal

A. Local variable assignment

In programming, alocal variableAssignment refers to the process of declaring and assigning variables within a specific scope, such as a function or code block.local variableare temporary and have limited visibility, i.e. they can only be accessed within a defined scope.

Here are some key featureslocal variableTask:

  • Local variables in bash are created inside functions or code blocks.
  • By default, variables declared inside a function are local to that function.
  • They are not accessible outside the function or block in which they are defined.
  • Local variables usually store temporary or intermediate values ​​within a specific context.

Here's an example in a Bash script.

#!/bin/bashmy_function() { local x=10 # local variable assignment echo $x}my_function # output: 10 echo $x # output: (nothing, variable is not defined outside the function)

In this example, the variableXIt is alocal variableundermy functionFunction. It can be accessed and used inside the function, but accessing it outside the function will cause an error because the variable is not defined in the outer scope.

B. Global variable assignment

Without scripting Bash,global variableCan be accessed throughout the script, regardless of the scope in which they are declared.global variableCan be accessed and modified from anywhere in the script, including inside functions.

Here are some key featuresglobal variableTask:

  • Global variables in bash are declared outside any function or block.
  • They can be accessed throughout the script.
  • By default, any variable declared outside a function or block is considered a global variable.
  • Global variables can be accessed and modified from anywhere in the script, including within functions.

Here is an examplescript bashgiven in the context of aglobal variable

#!/bin/bashx=10 # variable assignment globalmy_function() { x=$((x + 5)) # access and modify global variables echo $x}my_function # output: 15 echo $x # output: 15

Note that in bash, variables are assigned withoutlocal keywordsInside the function will create aglobal variableEven if a global variable with the same name exists. make surelocal scopeone insideFunction, it is recommended to use the local keyword explicitly.

Also, it's worth mentioning that subprocesses spawned by bash scripts, such as those run with$(...)orfreak, creating its own separate environment, and the variables assigned to these subprocesses inscript row

8 Different Situations of Assigning Variables in Bash Script

emscript bash, there are several situations or scenarios where you might need to assign variables. Here are some common situations that I describe below. These examples cover various scenarios such as allocatingUnivariate,Multiple variable assignments on a single line,Extract values ​​from command line arguments,Get user information,Using environment variables etc.. So let's get started.

Case 01: Single variable assignment

assign value to aUnivariateUmscript bash, you can use the following syntax:

variable = value

However, replaceChangingand the name of the variable to assign andcourageand the desired value you want to assign to that variable.

assign aunique valuefor a variablehit hard, you can do this:

Steps to follow >

❶ First, start afree terminal

❷ Write the following command to open the fileNano:

nano univariate.sh

explain

  • Nano:Open the file in the Nano text editor.
  • unique variable.sh: file name.

❸ Copy the script mentioned below:

#!/bin/bash#Assign integer variable var_int=23echo "Student ID: $var_int"

explain

first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. Next, the variablenocontains an integer value23and displayecho command

❹ pressureCTRL+Oeentersave document;CTRL+Xgo out.

❺ Use the following command to make the fileexecutable file:

chmod u+x variable_single.sh

explain

  • chmod: Change the permissions of files and directories.
  • you+x: here,youRefers"from user" orownerfile and+xSpecify the permissions to add, in this case "implement"Allowed. Whenyou+xAdded to the file permissions it grants the user (owner) execute permissions (running) document.
  • unique variable.sh: The name of the file to apply the permission to.

❻ Run the script with the following command:

./single_variable.sh

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (2)As shown in FIG,var_integerevariable stringThe variable returns the specified value23.

Case 02: Multiple variable assignment in a single line of Bash script

Assigning values ​​to multiple variables on a single line is a concise and efficient way to assign values ​​to multiple variables simultaneously in a programscript bash. This approach helps reduce the number of lines of code and can improve readability in some scenarios. Here's an example of a single-line multi-variable assignment.

You can followStages of Case 01, save the script and make the script executable.

Script (multi_variable.sh) >

#!/bin/bash#Multiple variables in a single line=1 y=2 z=3echo $xecho $yecho $z#Separate with semicolons var1="Hello"; var2="World" echo $var1 $var2#Merge and read command, assign value var3 var4 <<< "Hello LinuxSimply" echo $var3 $var4

explain

first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. Then,threevariableX,simulation, ezvalue is assigned1,2, e3, respectively. oxygenecho statementUsed to print the value of each variable. After that, two variablesvariable 1evariable 2value is assignedHello“e”world", respectively. Oxygensemicolon(;) Separates assignment statements on a single line. oxygenecho statementPrint the values ​​of two variables with a space between them. at last,read commandfor assigning tovariable 3and var4. oxygen<<is calledstring aqui, which allows the string "Hello Linux simple version" is passed asprohibitforread command. The input string is split into words and the first word is assigned tovariable 3, while the remaining words are attributed tovariable 4. at last,echo statementDisplay the values ​​of two variables.

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (3)here variableX,simulationezreturns an integer value1,2e3respectively.variable 1,variable 2look backHelloeworldseparated by spaces. Finally, the variablevariable 3evariable 4look backHelloeLinux simple versionrespectively.

Case 03: Assigning Variables from Command Line Arguments

emhit hard, you can assign variables from command line arguments using special variables calledpositional parameters. Below is a code sample to demonstrate.

You can followStages of Case 01, save the script and make the script executable.

Script (var_as_argument.sh) >

#!/bin/bash# Assign value from command line parameter name="$1"age="$2"city="$3"# Use variable echo "Name: $name" echo "Age: $age" echo "City: $city "

explain

Providedscript bashstart atShebang#!/bin/bash)usehit hardshell. The script assigns the first command line argument to the variableName, the second parameterage, the third parameterCity. oxygenpositional parameter $1,2 USD, e$3, which represent values ​​passed as command-line arguments when running the script. So the script usesecho statementDisplays the value of the specified variable.

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (4)After execution, a script with command line arguments (positional arguments)john,23,New YorkreturnName,age, eCitytherefore.

Case 04: Assign a value to the variable Environmental Bash

emhit hard, you can also assign the value of aenvironment variablefor a variable. In order to accomplish the task you can use the following commandsyntax:

variable name=$ENV_VARIABLE_NAME

but must be replacedENV_VARIABLE_NAMEreal name isenvironment variableYou want to assign. Here is a sample code for your perusal.

You can followStages of Case 01, save the script and make the script executable.

script (env_variable.sh) >

#!/bin/bash# get value from environment variable path_name=$USER# use this value in script echo "Current user value is: $path_name"

explain

first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. the value ofusersAn environment variable representing the current username is assigned to the Bash username variable. Then use the echo command to display the output.

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (5)In this specific case, the environment variableusersReturns the current usernameother

Case 05: Assignment of default values

emhit hard, you can assign a default value to a variable using the commandSyntax ${variable: -default}. Note that this default assignment will not changecourage originalvariable; he just assigns astandard valueIf the variable isemptyordisarm. Here's a script to see how it works.

You can followStages of Case 01, save the script and make the script executable.

script (default_variable.sh) >

#!/bin/bashvariable=""# If the variable is undefined or empty, give it a default value variable="${variable:-Softeko}" echo "$variable"# Set the value of the variable variable="LinuxSimply" # Since the variable is not empty, the default value is not used variable="${variable:-variable}"echo "$variable"

explain

first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. The next line stores the empty string inChanging. oh ${Variable: - Softeko} expression checks if the variable is undefined or empty. Since the variable is empty, it assigns a default value (softin this case) toChanging. In the second part of the code,Linux simple versionStrings are stored as variables. Then print the assigned variable usingecho command

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (6)The output after execution shows the default valuesoftfirst then return the assigned valueLinux simple versionOnce the variable gets the data.

Case 06: Assignment by obtaining user information

emhit hard, you can assign user values ​​with the commandleOrder. Remember, we used this command inCase 2. Instead of assigning values ​​in a single line,read commandAllows you to request user input and assign it to a variable. An example is given below.

You can followStages of Case 01, save the script and make the script executable.

script (user_variable.sh) >

#!/bin/bash# Prompt the user to enter echo "Enter your name: "Read name# Display the value entered by the user echo "Hello, $name!"

explain

first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. oxygenread commandfor reading user input and assigning it toname variable. The user will be prompted "Enter your name:", the values ​​they enter are stored in theNameChanging. Finally, the script displays a message with the entered value.

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (7)or immediate levaotheroffrom userand store the value inNameChanging. Then the output showsHello Milan!as the return value.

Case 07: Use the let command to assign values ​​​​to variables

emhit hard, Ølet orderCan be used asarithmetic operationand variable assignment. It allows you to perform arithmetic operations when assigning values ​​to variables using letassign the result to a variable

You can followStages of Case 01, save the script and make the script executable.

Script (let_var_assign.sh) >

#!/bin/bash# Perform arithmetic (addition) let "num = 5 + 3" echo "Value stored in variable num1 = $num1"

explain

first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. Solet orderPerform arithmetic operations and assign the result to a variableserial numberlater,echo commandused to display the storednumberChanging.

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (8)oxygenlet orderBag5e3, and store the return value innumberChanging. oxygennumbervariable display output8as "The value stored in the variable num1 = 8

Case 08: Assign shell command output to variable

Finally, you can assign the output of ashell commandto a variable usingcommand substitution. There are two common ways to achieve this: usefreak (”)or use$()Note on syntax$()syntax is usually better thanfreakbecause it provides betterreadabilityenestcapacity and avoid some quoting issues. Here are the examples I provided using both cases.

You can followStages of Case 01, save the script and make the script executable.

script (shell_command_var.sh) >

#!/bin/bash# Use backticks output1=`ls -l`echo "$output1"# Use $() syntax output2=$(data)echo "$output2"

explain

first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. Outputcommand ls -l(list the contents of the current directory in long form) assign to the variableExit 1usefreak. Similarly, the outputdate command(displays current date and time) Assign to output2 variable usingSyntax $(). oxygenecho commandshow bothExit 1eexit 2

How to assign variables in Bash script? 【8 Practical Cases】-LinuxSimply (9)here are twoExit 1eexit 2variable returns the output as above.

Variable assignment in Bash script

Finally, I assigned two assignments based on today's discussion. Don't forget to check it out.

  1. Create a Bash script that takes two numbers as input from the user and performs arithmetic operations using variables. The output should be similar to the following:
    • Soma:?
    • the difference: ?
    • product: ?
    • business: ?
    • The remaining: ?
  2. Write a Bash script that finds and displays the names of the largest files using a variable in a specified directory.

hint:For the second task you have to deployPara cycleand multipleloop if-elseIterate over every file in the current directory.

in conclusion

In summary, Bash variable assignment is an important aspect of scripting that allows developers to store and manipulate data efficiently. This article explores several scenarios for assigning variables in Bash, includingsingle variable assignment,Single-line multi-variable assignment,Assign values ​​to environment variables,etc. Each case has its advantages and limitations, and the choice depends on the specific needs of the script or program. However, if you have any questions about this article, feel free to leave a comment below. I will get back to you as soon as possible. Thanks!

people also ask

What is variable assignment?

Variable assignment is the process of assigning values ​​to variables in programming languages. It involves associating adata valueCommonvariable name, allowing the program to store and manipulate the value for later use.

How to assign variables to bash commands?

In Bash, you can assign the result of a command to a variable using the following syntax:variable = $(command)orvariable = `command`. you canreplaceThis command is the same asroyal orderyou want to run. The output of the command will contain a variable namedChanging

How to assign local variables in bash?

In Bash, you can assign a local variable inside a function usinglocal keywordsfollowed by the variable name andassignment operator(=) for the desired value.

What is the set command in bash?

oxygendefine commandNo Bash modification orshell environment variable,enable/disabledoptions, manipulationpositional parametersand controlcommand trace

rate this article

References

Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated: 04/12/2023

Views: 5892

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.