shell script Basics - variables

Posted by aboali on Fri, 21 Jan 2022 07:53:12 +0100

What are variables?

Variable is an indispensable part of any language, which is used to store all kinds of data. Scripting languages usually do not need to declare types before using variables, but only need to assign values directly.
Environment variables: some special variables will be used by shell script or operating system environment to store some special values. These variables are called environment variables and also called system variables.

Variable classification:

1. According to the function of variables
  • 1. User defined variable
  • 2. Environment variable: this variable mainly stores data related to the system operating environment.
  • 3. Location parameter variable: this variable is mainly used to transfer parameters or data to scripts. The variable name cannot be customized, and the function of the variable is fixed.
  • 4. Predefined variable: it is a variable defined in Bash. The variable name cannot be customized, and the function of the variable is fixed.
2. According to the scope of variables:
  • global variable
    A global variable is an environment variable whose value does not disappear with the execution of the shell script.
  • local variable
    Local variables are defined inside the shell program, and their scope of use is limited to the program that defines them, which is not visible to other programs. It includes user-defined variables, location variables and predefined variables.

environment variable

System defined variablessignificance
BASH=/bin/bashBash Shell name
BASH_VERSION=4.1.2(1)Bash version
HOME=/home/linuxtechiUser home directory
LOGNAME=LinuxTechiName of the currently logged in user
OSTYPE=LinuxOperating system type
PATH=/usr/bin:/sbin:/bin:/usr/sbinExecutable search path
PWD=/home/linuxtechiCurrent working directory
SHELL=/bin/bashShell name
USERNAME=linuxtechiCurrently logged in user name
[root@ecs-c13b ~]# echo $BASH
/bin/bash
[root@ecs-c13b ~]# echo $OSTYPE
linux-gnu
[root@ecs-c13b ~]# 

We can view the environment variables related to the process:

[root@ecs-c13b ~]# pgrep sshd
2970
29858
[root@ecs-c13b ~]# cat /proc/2970/environ 
LANG=en_US.UTF-8PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/binNOTIFY_SOCKET=/run/systemd/notifySSH_USE_STRONG_RNG=0[root@ecs-c13b ~]# 

User defined variable

Naming and rules of variables:
  1. Variables start with letters or underscores. It is not allowed to start with numbers, followed by letters, numbers or underscores, and the case meaning is different.
  2. When using a variable, you need to prefix the variable name$
  3. There must be no spaces on either side of the equal sign
  4. Superposition of variable values, using ${}
  5. Command replacement, use $() or backquotes
1) Variable rule test
[root@ecs-c13b ~]# 2eee=4      ## Cannot start with a number
-bash: 2eee=4: command not found
[root@ecs-c13b ~]# name=zhangshan   ### Case difference
[root@ecs-c13b ~]# NAME=lisi
[root@ecs-c13b ~]# echo $name
zhangshan
[root@ecs-c13b ~]# echo $NAME
lisi

2) About the use of ${}, splicing test
[root@ecs-c13b ~]# ctest=mysql
[root@ecs-c13b ~]# echo $ctest
mysql
[root@ecs-c13b ~]# echo $ctest-txt
mysql-txt
[root@ecs-c13b ~]# echo $ctest.db.log-txt
mysql.db.log-txt
[root@ecs-c13b ~]# echo {$ctest}db.log
{mysql}db.log
[root@ecs-c13b ~]# echo ${ctest}db.log
mysqldb.log

3) Can we not add {}?
[root@ecs-c13b ~]# echo $ctestdb.log-txt
.log-txt

4) Use backquotes or $()

[root@ecs-c13b ~]# echo date
date
[root@ecs-c13b ~]# echo $(date)
Wed Aug 5 15:53:03 CST 2020
[root@ecs-c13b ~]# echo date
Wed Aug 5 15:53:15 CST 2020
[root@ecs-c13b ~]#

5) Special usage
[root@ecs-c13b ~]# date +"%Y-%m"
2020-08

[root@ecs-c13b ~]# date +"%Y-%m-%d-%H%M%S"
2020-08-05-155600
[root@ecs-c13b ~]# 
date Command addition and subtraction:
date +%Y%m%d                   #Display the date of the day
date -d "+1 day" +%Y%m%d       #Show tomorrow's date
date -d "-1 day" +%Y%m%d       #Show yesterday's date
date -d "-1 month" +%Y%m%d     #Displays the date of the previous month
date -d "+1 month" +%Y%m%d     #Displays the date of the next month
date -d "-1 year" +%Y%m%d      #Displays the date of the previous year
date -d "+1 year" +%Y%m%d      #Displays the date of the next year

6) The difference between single quotation marks and double quotation marks
  • '' all characters in single quotation marks, including special characters ($, ', ` and \), will be interpreted as characters themselves and become ordinary characters.
  • In double quotation marks, all characters except $, ', ` and \ are interpreted as characters themselves, which have special meanings of "calling variable value", "reference command" and "escape character"

Note: \ escape character, the special symbol following \ will lose its special meaning and become an ordinary character. For example, $will output the "$" symbol instead of variable reference

[root@ecs-c13b ~]# name=zmgaosh
[root@ecs-c13b ~]# echo $name
zmgaosh
[root@ecs-c13b ~]# echo '$name'
$name
[root@ecs-c13b ~]# echo "$name"
zmgaosh

Special variable

Special variablemeaning
$$PID of Shell itself (ProcessID)
$!PID of the background Process last run by the Shell
$?End code of the last command run (return value)
$-List of flags Set with the Set command
$*List of all parameters. If "$*" is enclosed by ",", output all parameters in the form of "$1 $2... $n".
$@List of all parameters. If "$@" is enclosed by "", "$1" is used““ 2 " ... " 2" ... " 2. Output all parameters in the form of "..." n ".
$#Number of parameters added to Shell
$0The file name of the Shell itself
$1 to $nParameter values added to the Shell$ 1 is the first parameter, $2 is the second parameter.
Special variable instance
[root@ecs-c13b ~]# vim ex1
[root@ecs-c13b ~]# chmod +x ex1 
[root@ecs-c13b ~]# ./ex1 11  12 14
Shell Pass parameter instance!
Executed file name:./ex1
 The first parameter is: 11
 The second parameter is: 12
 The third parameter is: 14
[root@ecs-c13b ~]# 

Variable case

Exercise 1:
Simulate user login and display login user

[root@ecs-c13b ~]# vim login.sh
[root@ecs-c13b ~]# bash login.sh 
enter one user name: zmgaosh     
Please input a password: 123456
Login success,Welcome,zmgaosh
[root@ecs-c13b ~]# 

summary

This section is the shell part of the step-by-step operation and maintenance series - shell variables. Understanding variables is very helpful for our later learning.

Internet Lao Xin:
Internet programming craftsman, architect, a technology geek, a preacher; I have had a dream of being a lecturer since high school. After working for more than ten years, I have finally been lucky to become a cloud computing lecturer, continue to study the field of cloud computing and information security, and continue to sincerely teach my students what I have learned and felt, so as to help more small partners who want to enter the IT industry. Preach, teach and dispel doubts, know the great responsibility, and walk on thin ice every day. Study hard and move forward without any slack.

This article is from ID: Internet old Xin more content is concerned about the official account of the "geek operation and maintenance home".

Topics: shell