Linux bash setting variables

How To – Linux Set Environment Variables Command

  1. Configure look and feel of shell.
  2. Setup terminal settings depending on which terminal you’re using.
  3. Set the search path such as JAVA_HOME, and ORACLE_HOME.
  4. Create environment variables as needed by programs.
  5. Run commands that you want to run whenever you log in or log out.
  6. Set up aliases and/or shell function to automate tasks to save typing and time.
  7. Changing bash prompt.
  8. Setting shell options.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux
Est. reading time 11 minutes

Two types of shell variables

  • Environment variables (GLOBAL): Typically, end-users shouldn’t mess with Environment variables as they are available system-wide, and subshells and child processes can access them. In certain scenarios, we can modify them as per our needs. For example, we set up a system-wide path for the JAVA app or PATH for searching binaries. In almost all cases, we use the export command to define or modify environment variables.
  • Shell and user-defined variables (LOCAL) : As the name suggests, these are defined by users and currently apply to the current shell session.

You can use the following commands to view and configure the environment.

Display current environment variables on Linux

The printenv command shows all or the given environment variables. Open the terminal prompt and then type:
printenv
printenv VAR_NAME
printenv PS1
printenv ORACLE_HOME
printenv JAVA_HOME
# use the grep command/egrep command to filter out variables #
printenv | grep APP_HOME
printenv | egrep ‘APP_HOME|DOCKER_HOME|NIX_BACKUP_HOST’

env command

The env command runs a Linux command with a modified environment. The syntax is:

Please note that If no command name is specified following the environment specifications, the resulting environment is displayed on screen. This is like specifying the printenv command as discussed earlier. For example:

How to set and list environment variables in Linux using set command

The env command/printenv command displays only the Linux shell environment variables. What if you need to see a list of all variables, including shell, environment, user-defined shell functions? Try the following set command for printing environment variables:
set
set | grep BASH
Here is what we see:

The $PATH defined the search path for commands. It is a colon-separated list of directories in which the shell looks for commands. The $PS1 defines your prompt settings. See the list of all commonly used shell variables for more information. You can display the value of a variable using the printf command or echo command:

Outputs from the last command displaying my home directory location set by the $HOME environment variable on Linux:
/home/vivek

Источник

How to use Variables in Bash Programming

Using variable from command line or terminal

You don’t have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use ‘$’ symbol before the variable name when you want to read data from the variable. You can set and get data from a variable from the terminal in the following way.

Example-1: Declaring and reading string data using variable

Run the following commands from the terminal.

Output:

Example-2: Combining two string variables

You don’t have to use any operator to combine two or more strings like other languages. Here, $var1 is used to store string value and $var2 is used to store a numeric value. Run the following commands from the terminal to combine two variables $var1 and $var2.

Output:

**Note: You can print the value of the variable without any quotation but if you use quotations then you have to use double quotations.

Example-3: Concatenating strings with variables

Double quotation can be used to read the value of the variable. In this example, single quotation is used on one echo statement and double quotation is used on another echo statement. Run the following commands from the terminal to check the output.

Output:

Example-4: Declaring and reading numeric data using variables

One of the major limitations of Bash programming is that it can’t perform arithmetic operations like other programming languages. Numeric values are taken as strings in BASH. So no arithmetic operation can be done by normal expression and it just combines the numeric values. If you write the expression with double first bracket then the arithmetic operation works properly. Run the following commands from the terminal.

Output:

Example-5: Doing arithmetic operation using bc command

bc command is another way to do arithmetic operation in BASH. Run the following commands from the terminal. When you use bc command only for doing any arithmetic operation then fractional parts are omitted from the result. You have to use -l option with bc command to get the result with fractional value.

Output:

Using variables in bash file

You can define variable in bash file by the same way which are mentioned in above examples. You have to create file with .sh or .bash extension to run bash script.

Example-6: Creating simple bash script

Copy the following code in a text editor and save the file with bash extension. In this script, one string and one numeric variables are declared.

str = «Learn BASH Programming»

#print string value
echo $str

#subtract 20 from numeric variable
( ( result = $num — 20 ) )

#print numeric value
echo $result

Output:

Example-7: Using global and local variables

In the following script, one global variable n and two local variables n and m are used.
When the function addition() is called then the value of the local variable n is taken for calculation but global variable n remains unchanged.

#!/bin/bash
n = 5
function addition ( )
<
local n = 6
local m = 4
( ( n =n+m ) )
echo $n

Output:

Example-8: Using array variable

Array variable is used to store a list of data. The following example shows how you use of array variable in bash script. The elements of any array are separated by space in BASH. Here, an array of 6 elements is declared. There is no built-in function or property to count the total elements of the array. # with * is used to count total elements. All elements are indicated by *. For loop is used here to iterate the array values. Reading array values and array values with key are shown in the next part of this script.

myarr = ( HTML JavaScript PHP jQuery AngularJS CodeIgniter )

#Count total number of elements of the array
total = $ <#myarr[*]>
echo «Total elements: $total «

#Print each element value of the array
echo «Array values :»
for val in $
do
printf » %s \n » $val
done

#Print each element value of the array with key

echo «Array values with key:»
for key in $
do
printf «%4d: %s \n » $key $
done

Output:

To use BASH variables properly you need a clear concept on the declaration and use of variables. This tutorial will help you to get a clear idea on BASH variables. After exercising the above examples properly you will be able to use variables more efficiently in your bash scripts.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Bash Scripting Tutorial — 2. Variables

Variables!

Temporary stores of information

Introduction

For those of you that have dabbled in programming before, you’ll be quite familiar with variables. For those of you that haven’t, think of a variable as a temporary store for a simple piece of information. These variables can be very useful for allowing us to manage and control the actions of our Bash Script. We’ll go through a variety of different ways that variables have their data set and ways we can then use them.

Variables are one of those things that are actually quite easy to use but are also quite easy to get yourself into trouble with if you don’t properly understand how they work. As such there is a bit of reading in this section but if you take the time to go through and understand it you will be thankful you did later on when we start dabbling in more complex scripts.

How do they Work?

A variable is a temporary store for a piece of information. There are two actions we may perform for variables:

  • Setting a value for a variable.
  • Reading the value for a variable.

Variables may have their value set in a few different ways. The most common are to set the value directly and for its value to be set as the result of processing by a command or program. You will see examples of both below.

To read the variable we then place its name (preceded by a $ sign) anywhere in the script we would like. Before Bash interprets (or runs) every line of our script it first checks to see if any variable names are present. For every variable it has identified, it replaces the variable name with its value. Then it runs that line of code and begins the process again on the next line.

Here are a few quick points on syntax. They will be elaborated on and demonstrated as we go into more detail below.

  • When referring to or reading a variable we place a $ sign before the variable name.
  • When setting a variable we leave out the $ sign.
  • Some people like to always write variable names in uppercase so they stand out. It’s your preference however. They can be all uppercase, all lowercase, or a mixture.
  • A variable may be placed anywhere in a script (or on the command line for that matter) and, when run, Bash will replace it with the value of the variable. This is made possible as the substitution is done before the command is run.

Command line arguments

Command line arguments are commonly used and easy to work with so they are a good place to start.

When we run a program on the command line you would be familiar with supplying arguments after it to control its behaviour. For instance we could run the command ls -l /etc. -l and /etc are both command line arguments to the command ls. We can do similar with our bash scripts. To do this we use the variables $1 to represent the first command line argument, $2 to represent the second command line argument and so on. These are automatically set by the system when we run our script so all we need to do is refer to them.

Let’s look at an example.

mycopy.sh

  1. #!/bin/bash
  2. # A simple copy script
  3. cp $1 $2
  4. # Let’s verify the copy worked
  5. echo Details for $2
  6. ls -lh $2

Let’s break it down:

  • Line 4 — run the command cp with the first command line argument as the source and the second command line argument as the destination.
  • Line 8 — run the command echo to print a message.
  • Line 9 — After the copy has completed, run the command ls for the destination just to verify it worked. We have included the options l to show us extra information and h to make the size human readable so we may verify it copied correctly.
  1. ./mycopy.sh /projects/file1.data ./results.data
  2. Details for ./results.data
  3. -rw-r—r— 18 ryan users 3.4M Feb 14 07:18 results.data

We’ll discuss their usage a little more in the next section ( 3. Input ).

Other Special Variables

There are a few other variables that the system sets for you to use as well.

  • $0 — The name of the Bash script.
  • $1 — $9 — The first 9 arguments to the Bash script. (As mentioned above.)
  • $# — How many arguments were passed to the Bash script.
  • $@ — All the arguments supplied to the Bash script.
  • $? — The exit status of the most recently run process.
  • $$ — The process ID of the current script.
  • $USER — The username of the user running the script.
  • $HOSTNAME — The hostname of the machine the script is running on.
  • $SECONDS — The number of seconds since the script was started.
  • $RANDOM — Returns a different random number each time is it referred to.
  • $LINENO — Returns the current line number in the Bash script.

If you type the command env on the command line you will see a listing of other variables which you may also refer to.

Some of these variables may seem useful to you now. Others may not. As we progress to more complex scripts in later sections you will see examples of how they can be useful.

Setting Our Own Variables

As well as variables that are preset by the system, we may also set our own variables. This can be useful for keeping track of results of commands and being able to refer to and process them later.

There are a few ways in which variables may be set (such as part of the execution of a command) but the basic form follows this pattern:

This is one of those areas where formatting is important. Note there is no space on either side of the equals ( = ) sign. We also leave off the $ sign from the beginning of the variable name when setting it.

Variable names may be uppercase or lowercase or a mixture of both but Bash is a case sensitive environment so whenever you refer to a variable you must be consistent in your use of uppercase and lowercase letters. You should always make sure variable names are descriptive. This makes their purpose easier for you to remember.

Here is a simple example to illustrate their usage.

simplevariables.sh

  1. #!/bin/bash
  2. # A simple variable example
  3. myvariable=Hello
  4. anothervar=Fred
  5. echo $myvariable $anothervar
  6. echo
  7. sampledir=/etc
  8. ls $sampledir

Let’s break it down:

  • Lines 4 and 6 — set the value of the two variables myvariable and anothervar.
  • Line 8 — run the command echo to check the variables have been set as intended.
  • Line 9 — run the command echo this time with no arguments. This is a good way to get a blank line on the screen to help space things out.
  • Line 11 — set another variable, this time as the path to a particular directory.
  • Line 13 — run the command ls substituting the value of the variable sampledir as its first command line argument.
  1. ./simplevariables.sh
  2. Hello Fred
  3. a2ps.cfg aliases alsa.d .

It is important to note that in the example above we used the command echo simply because it is a convenient way to demonstrate that the variables have actually been set. echo is not needed to make use of variables and is only used when you wish to print a specific message to the screen. (Pretty much all commands print output to the screen as default so you don’t need to put echo in front of them.)

Variables can be useful for making our scripts easier to manage. Maybe our script is going to run several commands, several of which will refer to a particular directory. Rather than type that directory out each time we can set it once in a variable then refer to that variable. Then if the required directory changes in the future we only need to update one variable rather than every instance within the script.

Quotes

In the example above we kept things nice and simple. The variables only had to store a single word. When we want variables to store more complex values however, we need to make use of quotes. This is because under normal circumstances Bash uses a space to determine separate items.

  1. myvar=Hello World
  2. -bash: World: command not found
  • Remember, commands work exactly the same on the command line as they do within a script.

Because commands work exactly the same on the command line as in a script it can sometimes be easier to experiment on the command line.

When we enclose our content in quotes we are indicating to Bash that the contents should be considered as a single item. You may use single quotes ( ‘ ) or double quotes ( » ).

  • Single quotes will treat every character literally.
  • Double quotes will allow you to do substitution (that is include variables within the setting of the value).
  1. myvar=’Hello World’
  2. echo $myvar
  3. Hello World
  4. newvar=»More $myvar»
  5. echo $newvar
  6. More Hello World
  7. newvar=’More $myvar’
  8. echo $newvar
  9. More $myvar

Command Substitution

Command substitution allows us to take the output of a command or program (what would normally be printed to the screen) and save it as the value of a variable. To do this we place it within brackets, preceded by a $ sign.

  1. myvar=$( ls /etc | wc -l )
  2. echo There are $myvar entries in the directory /etc

Command substitution is nice and simple if the output of the command is a single word or line. If the output goes over several lines then the newlines are simply removed and all the output ends up on a single line.

  1. ls
  2. bin Documents Desktop .
  3. Downloads public_html .
  4. myvar=$( ls )
  5. echo $myvar
  6. bin Documents Desktop Downloads public_html .

Let’s break it down:

  • Line 1 — We run the command ls. Normally its output would be over several lines. I have shortened it a bit in the example above just to save space.
  • Line 4 — When we save the command to the variable myvar all the newlines are stripped out and the output is now all on a single line.

When playing about with command substitution it’s a good idea to test your output rather than just assuming it will behave in a certain way. The easiest way to do that is simply to echo the variable and see what has happened. (You can then remove the echo command once you are happy.)

Exporting Variables

Remember how in the previous section we talked about scripts being run in their own process? This introduces a phenomenon known as scope which affects variables amongst other things. The idea is that variables are limited to the process they were created in. Normaly this isn’t an issue but sometimes, for instance, a script may run another script as one of its commands. If we want the variable to be available to the second script then we need to export the variable.

script1.sh

  1. #!/bin/bash
  2. # demonstrate variable scope 1.
  3. var1=blah
  4. var2=foo
  5. # Let’s verify their current value
  6. echo $0 :: var1 : $var1, var2 : $var2
  7. export var1
  8. ./script2.sh
  9. # Let’s see what they are now
  10. echo $0 :: var1 : $var1, var2 : $var2

script2.sh

  1. #!/bin/bash
  2. # demonstrate variable scope 2
  3. # Let’s verify their current value
  4. echo $0 :: var1 : $var1, var2 : $var2
  5. # Let’s change their values
  6. var1=flop
  7. var2=bleh

Now lets run it and see what happens.

  1. ./script1.sh
  2. script1.sh :: var1 : blah, var2 : foo
  3. script2.sh :: var1 : blah, var2 :
  4. script1.sh :: var1 : blah, var2 : foo

The output above may seem unexpected. What actually happens when we export a variable is that we are telling Bash that every time a new process is created (to run another script or such) then make a copy of the variable and hand it over to the new process. So although the variables will have the same name they exist in separate processes and so are unrelated to each other.

Exporting variables is a one way process. The original process may pass variables over to the new process but anything that process does with the copy of the variables has no impact on the original variables.

Exporting variables is something you probably won’t need to worry about for most Bash scripts you’ll create. Sometimes you may wish to break a particular task down into several separate scripts however to make it easier to manage or to allow for reusability (which is always good). For instance you could create a script which will make a dated (ie todays date prepended to the filename) copy of all filenames exported on a certain variable. Then you could easily call that script from within other scripts you create whenever you would like to take a snapshot of a set of files.

Summary

Activities

Let’s explore variables.

  • A good place to start is to create a simple script which will accept some command line arguments and echo out some details about them (eg, how many are there, what is the secone one etc).
  • Create a script which will print a random word. There is a file containing a list of words on your system (usually /usr/share/dict/words or /usr/dict/words). Hint: Piping will be useful here.
  • Expand the previous activity so that if a number is supplied as the first command line argument then it will select from only words with that many characters. Hint: Grep may be useful here.
  • Take a copy of the two files script1.sh and script2.sh above then experiment by tweaking them and running them and observing the output. This will help you get a feel for how exporting variables works.
  • Now let’s create a script which will take a filename as its first argument and create a dated copy of the file. eg. if our file was named file1.txt it would create a copy such as 2021-10-10_file1.txt. (To achieve this you will probably want to play with command substitution and the command date)
  • Challenge: To make it a bit harder, see if you can get it so that the date is after the name of the file (eg. file1_2021-10-10.txt (The command basename can be useful here.)
  • Challenge: Now see if you can expand the previous question to accept a list of files on the command line and it will create a named copy of all of them. (The command xargs may be useful here.)

Источник

Читайте также:  Изменение даты линукс терминал
Оцените статью