Shell Variable

When you define the a variable name, the name should not prefix $(excepting in PHP ),for example

your_name="www.linuxcommands.site"

We should not add blank space between the variable name and the equal sign which is different among your similar program languages.The defining of variable name should accord the following rules:

  • The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).The first character can not be the numbers.
  • The name of a variable can not contain blank space, can use underscore character.
  • Can not use punctuation mark.
  • Can not use the keyword in bash(You can use command help to get the reserved keyword)

The following examples are valid variable names

LINUXCOMMANDS
LD_LIBRARY_PATH
_var
var2

Following are the examples of invalid variable names

?var=123
user*name=linuxcommands

We also can define the variable name by getting variable contents from a file ,for example

for file in `ls /etc`
or
for file in $(ls /etc)

Accessing Values

To access the value stored in a variable, prefix its name with the dollar sign ($)

For example

your_name="linuxcommands"
echo $your_name
echo ${your_name}

The curly braces outside the variable name are optional, and they can be added or not. The curly braces are added to help the interpreter to recognize the boundary of the variable, such as the following:

for skill in Ada Coffe Action Java; do
    echo "I am good at ${skill}Script"
done

If you do not add curly braces to the variable ‘skill’ and write like “I am good at $ skillScript”, the interpreter will treat $ skillScript as a variable (its value is empty), and the code execution result is what we don’t expected.

It is recommended to add curly braces to all variables, which is a good programming habit.

The defined variables can be redefined, such as:

your_name="tom"
echo $your_name
your_name="linuxcommands"
echo $your_name

It is legal to write this way,We notice that we cannot write prefix $ and variable name when we assign the value for the second time.We only access the variables by using the dollar sign ($).

Read-only Variables

Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed.

For example, the following script generates an error while trying to change the value of myUrl

#!/bin/bash 
myUrl="http://www.google.com" 
readonly myUrl 

myUrl="www.linuxcommands.site"

The above script will generate the following result 

/bin/sh: NAME: This variable is read only.

Deleting Variables

Following is the syntax to delete a defined variable using the unset command

unset variable_name

Once you unset a variable, you cannot access the stored value in the variable.The readonly variable can not be deleted.

#!/bin/sh
myUrl="http://www.linuxcommands.site"
unset myUrl
echo $myUrl

The above script will be no results

Variable Types

When a shell is running, three main types of variables are present

  • Local Variables − A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at the command prompt.
  • Environment Variables − An environment variable is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually, a shell script defines only those environment variables that are needed by the programs that it runs.
  • Shell Variables − A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables.

Shell Strings

String is a impornant,useful data type in shell(Except numbers and strings ).We can define by using single quotes or double quotes or no quotation marks.The diffenence between single quotes and double quotes is similar to the PHP.

Single quotes

str='this is a string'

Restrictions on single quoted strings:

  • Any characters in single quotes will be output as they are, and the variables in single quote strings are invalid;
  • A single quotation mark cannot appear in a single quotation string (using an escape character also can not be appeared), but it can appear in pairs and be used as a string concatenation.

Double quotes

your_name='linuxcommands'
str="Hello, I know you are \"$your_name\"! \n"
echo -e $str

The result is

Hello, I know you are "linuxcommands"! 
The advantages of double quotes:
  • The variable names can be used in doublequote strings
  • Escape characters can appear in double quotes

Concatenating Strings

your_name="linuxcommands"
# Concatenating by single quote
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting  $greeting_1
# Concatenating by double quote
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2  $greeting_3

String Length

string="abcd"
echo ${#string} #output 4

Substring Extraction

Extract substring of length $LEN(4) from $STRING starting after position $POS(1). Note that first position is 0.

string="linuxcommands is a great site"
echo ${string:1:4} # output inux

Substring Finding

Find the position of the charater i  or o,we will find

which is the first appear in substring.

string="linuxcommands is a great site"
echo `expr index "$string" io`  # output 2

Note: `in the above script is back quotes, not single quotes, don’t read it wrong.


Shell Arrays

Bash supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no limit to the size of the array.

The subscripts of array elements are numbered from 0 which is similar to the C language.We can obtain the elements by array subscripts. Subscripts can be integers or arithmetic expressions, and their values ​​should be greater than or equal to 0.

Defining Array Values

In the shell, the parentheses are used to represent the array, and the array elements are separated by the “space” symbol.The general form of defining an array is:

Array Values=(value1 value2 ... valueN)
For Example:
array_name=(value0 value1 value2 value3)

Or

array_name=(
value0
value1
value2
value3
)

We can also define the individual array element:

array_name[0]=value0
array_name[1]=value1
array_name[n]=valueN

It is not necessary to use continuous subscripts, and the range of subscripts is not limited.

Accessing Array Values

The general format for access array element values ​​is:

${array_name[index]}

We can access all array elements by using @, for example:

echo ${array_name[@]}

Array Length

The method to obtain the length of the array is the same as the string’s, for example:

# getting all the items's length
length=${#array_name[@]}
# 或者
length=${#array_name[*]}
# getting the array_name[n]'s length
lengthn=${#array_name[n]}

Shell Comments

A word or line beginning with # causes that is the shell comments which word and all remaining characters on that line to be ignored by Interpreter.

#--------------------------------------------
# These are shell comments
# author:linuxcommands
# site:www.linuxcommands.site
#--------------------------------------------
##### User Setting Begin #####
#
#
# Scripts Comments
# 
#
##### User Setting End  #####

Multiple Line Comment

We can use the following format:

:<<EOF 
Comment contents... 
Comment contents... 
Comment contents... 
EOF

EOF can also replace by other symbols:

:<<'
Comment contents...
Comment contents...
Comment contents...
'

:<<!
Comment contents...
Comment contents...
Comment contents...
!

Add a Comment

Your email address will not be published.