Lal»Bash scripting tutorial»bash variables»Variable declaration and assignment»How to declare variables in Bash script? 【5 actual cases】
script bash
Muhammad Xia Milan July 31, 2023
Like other programming languages,script bashIt really depends on your variables. so understandHow to declare variables and create them in BashEssential for effective script development. In this article, I'll delve into the basic concepts of declaring variables inscript bash. i will exploreSyntax for declaring variables, discussvarious types of dataYou can make assignments and discover examples to understand the practice of declaring variables in code. So let's get started.
index expansion
main conclusion
- Learn the basic syntax of variable declarations.
- Learn about options used in variable declarations.
- Learn variable declarations for different data types.
free download
Download exercise files
Declarative commands in Bash scripts
In a Bash script, you can useannounce orderclear statementvariableand set yourAttributes. It provides additional control over variables beyond the simple assignment syntax.
declare [options] variable name = value
useful options
useoptionsasannounce orderProvides explicit control and customization of variable declarations. These options allow you to imposespecific data type,Declare a read-only variable,export variableFor the environment,show variable properties,ETC。
Here are some common options for declarative commands:
options | describe |
---|---|
-European Union | Declare an integer variable. |
-A | Declare an array variable. |
-A | Declare an associative array variable. |
-F | Declare a function. |
-European Union | Convert variable value to lowercase. |
-you | Convert variable value to uppercase. |
-r | Declare a read-only variable. |
-X | Declare an exportable variable. |
-p | Display property and variable values. |
-G | Declare the variable as global (available at function scope). |
-n | Treats the variable as undefined (no value assigned). |
-t | Declare a variable as a trace option. |
-X | Declare the variable as automatically exported. |
To learn more, read:The "declare" command in Linux [7 practical examples]
5 cases of declaring variables in Bash script
In the following sections, I will give five different cases of using options in variable declarations. Knowing and practicing these cases will give you a better understandingvariable declaration。
Case 01: Variable declaration without options
when declaring a variableno option, Bash treats them asropego throughstandard. This allows flexible storage and manipulation of text-based data in scripts.
❶ First, start afree terminal。
❷ Write the following command to open the fileNano:
nano-var_declare_without_option.sh
explain
- Nano:Open the file in the Nano text editor.
- var_declare_without_option.sh:file name.
❸ Copy the script mentioned below in your Nano editor:
#!/bin/bash#Declare a variable without value declarevariable1#Declare a variable without options and value declare --variable2#Create a variable with value declarevariable3="Hello"#Print variable output echo $variable1echo $varibale2echo $ variable3
explain
here,#! /bin/bash: '#!', calledShebangorhash explosion. he pointed outInterpretersfor running the script, in this case thethe party. Next, the code declares three separate variables namedvariable 1,variable 2, evariable 3. Since there is no assignment tovariable 1evariable 2, which are defined asInvalidorempty string. By default, variables in Bash scripts are treated as strings unless otherwise specified. later,echo commandis used forprint valuestored in these three variables.
❹ pressureCTRL+Oeentersave the file; thenCTRL+Xgo out.
❺ Use the following command to make the fileexecutable file:
chmod u+x Var_declare_without_option.sh
explain
- chmod: Used to 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) file execution permissions (running) document.
- var_declare_without_option.sh: Screenplay name.
➏ Finally, run the script with:
./var_declare_without_option.sh
The output simply gives the values consisting of three variables,variable 1,variable 2, evariable 3。variable 1ethey are gay 2look backInvalidoutput because they contain no value, whilevariable 3return the goodsHelloas an export.
Case 02: Create whole variable with -i option
oxygen-i optionlets you accept a variable likeallform. For your understanding, a user case is presented below.
You can followStages of Case 01, save the script and make the script executable.
Script (Var_declare_with_i_option.sh)>
#!/bin/bash#Use the -i option to declare an integer variable declaration -i var#Get from the integer value read by the user -p "Enter a number:" var#Print the input value echo "provided integer value is $var"
explain
In this code,ShebangWire#!/bin/bashSpecifies that the script should be run withbash interpreter. later,var variableis declared asinteger variable. oxygenleia-pThis command is used to prompt the user to enter a value. Thenecho commandwill printeracourage.
Now run the script with:
./var_declare_with_i_option.sh
When the user enters4like dataeravariable, the output message will be "The supplied integer value is 4"
Case 03: Declaring and creating an array with the -a option
statementarray variableno script bash, o- an optionasannounce orderIt is used. oxygenarray variableProvides a convenience method for working with collections of data.
You can followStages of Case 01, save the script and make the script executable.
Screenplay (Var_declare_with_a_option.sh)>
#!/bin/bash#Use the -i option to declare an index array variable declare -a var_array#Get the array value from the user read -p "Enter the array value: " var_arrayecho "The input array value is: "# print the array ${var_array [@]}doecho the value of the value in $valuedone
explain
In this code,ShebangWire#!/bin/bashSpecifies that the script should be run using the Bash interpreter. Wiredeclare -a var_arraydeclare a variable namedvariable arrayas aindex arrayuse-A options. this meansvariable arrayCan hold onseveral valueslike an array. oxygenleia-pThis command allows the user to provide an array value. later onePara cyclemerged to show each element contained invariable array。
Now run the script with:
./var_declare_with_a_option.sh
Here, the user enters someall,float, eKedavalue as elementvariable array. echo command then displays the given value23 234 45 12 Fan 2.45With the help of a for loop.
Case 04: Declaring an uppercase string with the -u option
Instead of declaring different data types, you can use-you optionsDo yourselfKedaUmuppercase letterform. This is another case described below.
You can followStages of Case 01, save the script and make the script executable.
Script (Var_declare_with_u_option.sh)>
#!/bin/bash#Declare a string variable with an uppercase value declare -u upstringread -p "Enter string value:" upstring#Print variable echo "The uppercase form of the given string is $upstring"
explain
In this code, the shebang line#!/bin/bashSpecifies that the script should be run withbash interpreter. Wiredeclare -u upstringdeclare a variable namedget nervousAs a string with uppercase values, use-youoption. this meansget nervouswill be converted touppercase letter. oxygenleia-pThis command allows the user to provide any string value. oxygenecho commanddisplay the given stringuppercase letter。
Now run the script with:
./var_declare_with_u_option.sh
In this code, the option-youturnsimple linuxUmsimple linuxoutput displayThe uppercase form of the given string is LINUXSIMPLY。
Case 05: Declare and create a read-only variable with the -r option
In some cases, developers like you prefer to store someimmutableThe value in the script for later use. These variables are calledle–only variable. Europe"-r" option to declare variables in bash and create ale–onlyChanging. When a variable is marked asle–only, your valuecannot be modifiedortransfer inthroughout the execution of the script.
You can followStages of Case 01, save the script and make the script executable.
Script (Var_declare_with_i_option.sh)>
#!/bin/bash# Declare and create a read-only variable declaration -r MY_VARIABLE="Hello world!" # Attempt to modify the value (will cause an error) MY_VARIABLE="new value" # Print the read value -only variable echo " The read-only variable provided is $MY_VARIABLE"
explain
In this code, the shebang line#!/bin/bashSpecifies that the script should be run withbash interpreter. So the code stores "Hello world"themmy variable. Subsequently, the code tries to modifyle–onlyChangingmy variableAssign it a new value, "Novo courage". However, since the variable is declared asle–only, this line produces an error. Finally, the code displays the data stored inmy variableasecho command。
Now run the script with:
./var_declare_with_r_option.sh
As shown, the first line shows an error because the corresponding script line tries to change the datamy variable. However, the output says "The read-only variable provided isHello World!" as its initial value.
in conclusion
to finish,Declare variables in BashScripts are important because it allows you to store and manipulate data in scripts as needed. In this tutorial, I discuss various ways of declaring variables inscript bash. However, there are many more cases for declaring variables. So don't stop and explore further. If you have any questions about this article, feel free to leave a comment below.
people also ask
How to declare commands in bash?
declare a commandhit hard, just type the command followed by any required parameters and switches.
How to assign variables to variables in bash?
To assign the value of one variable to another in Bash, you can use the following syntaxvariable2="$variable1"。
What is $$ in bash script?
In a Bash script,$$is a special variable representingProcessor ID (PID)The currently running script or shell. It is a system-generated identifier assigned to every running process, including the script itself.
How to add value instead of bash?
To add values in Bash you can usearithmetic expansionsyntax.result=$((value1 + value2)). replaceBravery 1evalue 2with the actual value you want to add. The result will be stored in the result variable.
rate this article