Monday, 7 October 2019

How to Work with Variables in Bash

A Linux terminal with green text on a laptop.
Fatmawati Achmad Zaenuri/Shutterstock

Variables are vital if you want to write scripts and understand what that code you’re about to cut and paste from the web will do to your Linux computer. We’ll get you started!

Variables 101

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

Examples

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, this_year:

me=Dave
my_boost=Linux
him=Popeye
his_boost=Spinach
this_year=2019

Five variables in a terminal window.

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name
echo $my_boost
echo $this_year

The "echo" command displaying the values of variables in a terminal window.

Let’s use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

Read the remaining 64 paragraphs



from How-To Geek https://ift.tt/35fPBHa

No comments:

Post a Comment