theshell.ch/site/pages/scripts/1-variables.html
terehm 64f1910f34 css-team: spellcheck
git-svn-id: svn+ssh://atelier.inf.usi.ch/home/bevilj/group-1@280 a672b425-5310-4d7a-af5c-997e18724b81
2018-11-19 15:05:42 +00:00

95 lines
2.1 KiB
HTML

---
layout: page
category-page: scripts
category-title: Scripting
tags: variables defining deleting naming
author: Dario Rasic
title: Script Variables
previous-page: pages/scripts/0-base-commands.html
next-page: pages/scripts/2-special-variables.html
---
<!-- Intro -->
A variable is simply a string to which we assign a certain type of data,
which could be some text, a number, a filename or other types of data.<br>
<!-- How to name a variable - text -->
<h3>Naming a variable</h3>
<!-- Explaination -->
To name a variable in Unix we can only use letters, numbers or
the underscore character (_).<br>
Other characters can't be used because they have a special meaning in Unix Shell.<br>
Some simple examples are:
<pre>
VAR_1
VAR_2
NAME_3
name_4
</pre>
<!-- How to define a variable - text -->
<h3>Defining a variable</h3>
To define a certain variable, we use the following base case:
<pre>
variable_name=variable_value
</pre>
<!-- Examples of defining -->
Let me show you a simple example:
<pre>
VAR_1=Strawberry
</pre>
<!-- How to access the variables - text -->
To access a variable we have to use the dollar sign ($). So if I want to
access VAR_1, I have to write:
<!-- Examples of accessing -->
<pre>
VAR_1="Strawberry"
echo $VAR_1
Strawberry
</pre>
<!-- How to delete a variable - text -->
<h3>Deleting a variable</h3>
Deleting a variable means that the shell will remove a certain variable from the list of
those that it tracks.<br>
To delete a variable we use the following command:
<pre>
unset variable_name
</pre>
which in our case would be:
<pre>
unset VAR_1
</pre>
<!-- How to protect a variable - text -->
<h3>Protecting variables</h3>
To protect a certain variable, we can set it as read-only so that it can't be
changed or deleted.<br>
So, if we try to change the value of VAR_1, the result will be the following:
<pre>
VAR_1="Strawberry"
readonly VAR_1
VAR_1="Blueberry"
VAR_1: This variable is read only.
</pre>
If we try to delete the variable, the shell will give us the following error:
<pre>
VAR_1="Strawberry"
unset VAR_1
VAR_1: This variable is read only.
</pre>