shell script-variable

Posted by mapostel on Wed, 05 Jan 2022 09:08:40 +0100

Naming requirements:

  • Case sensitive
  • You cannot use reserved words in programs such as if, for...
  • Only numbers, letters, and underscores can be used, and cannot start with a number. Short dashes'-'are not supported, as opposed to hostnames.

Naming habits:

  • Know what you mean, name it in English words, and reflect the actual effect. Do not use abbreviations
  • Uniform naming rules:
    • Hump nomenclature: studentname
      • Camel: StudentName
      • Camel: studentName
  • Uppercase variable names: STUDENT_NAME
  • Local variable lowercase
  • Lowercase function name

Variable Definition and Reference

  • Common variable: The effective range is the current shell process; Invalid for shell processes other than the current shell and their child shells
  • Environment variable: The effective range is for the current shell process and its child shell processes
  • Local variable: The effective range is a snippet of code in the current shell process, usually a function

Variable assignment

name='value'

value can take many forms

Direct string: name='root'
Variable reference: name="$USER"
Command reference: name=`COMMAND` or name=$(COMMAND)

Note: Variable assignments are temporary. When you exit the terminal, variables are automatically deleted and cannot be persisted. Variables in scripts are automatically deleted as the script ends.

Variable References

$name
${name}

Weak and strong references

  • '$name'weak reference, where the variable is replaced by the variable value
  • '$name'strong reference, where the variable remains the original string

Examples: Various assignments and references to variables

[root@CentOS7 ~]# TITLE='cto'
[root@CentOS7 ~]# echo $TITLE
cto
[root@CentOS7 ~]# echo I am $TITLE
I am cto
[root@CentOS7 ~]# echo "I am $TITLE"
I am cto
[root@CentOS7 ~]# echo 'I am $TITLE'
I am $TITLE
[root@CentOS7 ~]# NAME=$USER
[root@CentOS7 ~]# echo $NAME
root
[root@CentOS7 ~]# USER=`whoami`
[root@CentOS7 ~]# echo $USER
root
[root@CentOS7 ~]# FILE=`ls /etc`
[root@CentOS7 ~]# echo $FILE
adjtime aliases aliases.db alternatives anacrontab asound.conf at.deny audisp audit bash_completion.d bashrc binfmt.d centos-release centos-release-upstream chkconfig.d cron.d cron.daily cron.deny cron.hourly cron.monthly crontab cron.weekly crypttab csh.cshrc csh.login dbus-1 default depmod.d dhcp DIR_COLORS DIR_COLORS.256color DIR_COLORS.lightbgcolor dracut.conf dracut.conf.d e2fsck.conf environment ethertypes exports exports.d favicon.png filesystems firewalld fstab fuse.conf gcrypt gnupg GREP_COLORS groff group group- grub2.cfg grub.d gshadow gshadow- gss gssproxy host.conf hostname hosts hosts.allow hosts.deny idmapd.conf init.d inittab inputrc iproute2 issue issue.net kdump.conf kernel krb5.conf krb5.conf.d ld.so.cache ld.so.conf ld.so.conf.d libaudit.conf libnl libuser.conf locale.conf localtime login.defs logrotate.conf logrotate.d lsb-release.d lvm machine-id magic mail.rc makedumpfile.conf.sample man_db.conf mke2fs.conf modprobe.d modules-load.d motd mtab my.cnf my.cnf.d netconfig NetworkManager networks nfs.conf nfsmount.conf nsswitch.conf nsswitch.conf.bak openldap opt os-release pam.d passwd passwd- pkcs11 pki plymouth pm polkit-1 popt.d postfix ppp prelink.conf.d printcap profile profile.d protocols python rc0.d rc1.d rc2.d rc3.d rc4.d rc5.d rc6.d rc.d rc.local redhat-lsb redhat-release request-key.conf request-key.d resolv.conf rpc rpm rsyslog.conf rsyslog.d rwtab rwtab.d sasl2 securetty security selinux services sestatus.conf shadow shadow- shells skel ssh ssl statetab statetab.d subgid subuid sudo.conf sudoers sudoers.d sudo-ldap.conf sysconfig sysctl.conf sysctl.d systemd system-release system-release-cpe terminfo tmpfiles.d tuned udev vconsole.conf vimrc virc vmware-tools wgetrc wpa_supplicant X11 xdg xinetd.d yum yum.conf yum.repos.d
[root@CentOS7 ~]# FILE=/etc/*
[root@CentOS7 ~]# echo $FILE
/etc/adjtime /etc/aliases /etc/aliases.db /etc/alternatives /etc/anacrontab /etc/asound.conf /etc/at.deny /etc/audisp /etc/audit /etc/bash_completion.d /etc/bashrc /etc/binfmt.d /etc/centos-release /etc/centos-release-upstream /etc/chkconfig.d /etc/cron.d /etc/cron.daily /etc/cron.deny /etc/cron.hourly /etc/cron.monthly /etc/crontab /etc/cron.weekly /etc/crypttab /etc/csh.cshrc /etc/csh.login /etc/dbus-1 /etc/default /etc/depmod.d /etc/dhcp /etc/DIR_COLORS /etc/DIR_COLORS.256color /etc/DIR_COLORS.lightbgcolor /etc/dracut.conf /etc/dracut.conf.d /etc/e2fsck.conf /etc/environment /etc/ethertypes /etc/exports /etc/exports.d /etc/favicon.png /etc/filesystems /etc/firewalld /etc/fstab /etc/fuse.conf /etc/gcrypt /etc/gnupg /etc/GREP_COLORS /etc/groff /etc/group /etc/group- /etc/grub2.cfg /etc/grub.d /etc/gshadow /etc/gshadow- /etc/gss /etc/gssproxy /etc/host.conf /etc/hostname /etc/hosts /etc/hosts.allow /etc/hosts.deny /etc/idmapd.conf /etc/init.d /etc/inittab /etc/inputrc /etc/iproute2 /etc/issue /etc/issue.net /etc/kdump.conf /etc/kernel /etc/krb5.conf /etc/krb5.conf.d /etc/ld.so.cache /etc/ld.so.conf /etc/ld.so.conf.d /etc/libaudit.conf /etc/libnl /etc/libuser.conf /etc/locale.conf /etc/localtime /etc/login.defs /etc/logrotate.conf /etc/logrotate.d /etc/lsb-release.d /etc/lvm /etc/machine-id /etc/magic /etc/mail.rc /etc/makedumpfile.conf.sample /etc/man_db.conf /etc/mke2fs.conf /etc/modprobe.d /etc/modules-load.d /etc/motd /etc/mtab /etc/my.cnf /etc/my.cnf.d /etc/netconfig /etc/NetworkManager /etc/networks /etc/nfs.conf /etc/nfsmount.conf /etc/nsswitch.conf /etc/nsswitch.conf.bak /etc/openldap /etc/opt /etc/os-release /etc/pam.d /etc/passwd /etc/passwd- /etc/pkcs11 /etc/pki /etc/plymouth /etc/pm /etc/polkit-1 /etc/popt.d /etc/postfix /etc/ppp /etc/prelink.conf.d /etc/printcap /etc/profile /etc/profile.d /etc/protocols /etc/python /etc/rc0.d /etc/rc1.d /etc/rc2.d /etc/rc3.d /etc/rc4.d /etc/rc5.d /etc/rc6.d /etc/rc.d /etc/rc.local /etc/redhat-lsb /etc/redhat-release /etc/request-key.conf /etc/request-key.d /etc/resolv.conf /etc/rpc /etc/rpm /etc/rsyslog.conf /etc/rsyslog.d /etc/rwtab /etc/rwtab.d /etc/sasl2 /etc/securetty /etc/security /etc/selinux /etc/services /etc/sestatus.conf /etc/shadow /etc/shadow- /etc/shells /etc/skel /etc/ssh /etc/ssl /etc/statetab /etc/statetab.d /etc/subgid /etc/subuid /etc/sudo.conf /etc/sudoers /etc/sudoers.d /etc/sudo-ldap.conf /etc/sysconfig /etc/sysctl.conf /etc/sysctl.d /etc/systemd /etc/system-release /etc/system-release-cpe /etc/terminfo /etc/tmpfiles.d /etc/tuned /etc/udev /etc/vconsole.conf /etc/vimrc /etc/virc /etc/vmware-tools /etc/wgetrc /etc/wpa_supplicant /etc/X11 /etc/xdg /etc/xinetd.d /etc/yum /etc/yum.conf /etc/yum.repos.d
[root@CentOS7 ~]# seq 10
1
2
3
4
5
6
7
8
9
10
[root@CentOS7 ~]# NUM=`seq 10`
[root@CentOS7 ~]# echo $NUM
1 2 3 4 5 6 7 8 9 10
[root@CentOS7 ~]# echo "$NUM"
1
2
3
4
5
6
7
8
9
10
[root@CentOS7 ~]# NAMES="wang
> zhang
> zhao
> li"
[root@CentOS7 ~]# echo $NAMES
wang zhang zhao li
[root@CentOS7 ~]# echo "$NAMES"
wang
zhang
zhao
li
[root@CentOS7 ~]# 

Example: Variable reference

[root@CentOS7 ~]# NAME=mage
[root@CentOS7 ~]# AGE=20
[root@CentOS7 ~]# echo $NAME
mage
[root@CentOS7 ~]# echo $AGE
20
[root@CentOS7 ~]# echo $NAME $AGE
mage 20
[root@CentOS7 ~]# echo $NAME$AGE
mage20
[root@CentOS7 ~]# echo $NAME_$AGE
20
[root@CentOS7 ~]# echo ${NAME}_$AGE
mage_20

Example: Indirect assignment and reference of variables

[root@CentOS7 ~]# TITLE=cto
[root@CentOS7 ~]# NAME=wang
[root@CentOS7 ~]# TITLE=$NAME
[root@CentOS7 ~]# echo $NAME
wang
[root@CentOS7 ~]# echo $TITLE
wang
[root@CentOS7 ~]# NAME=mage
[root@CentOS7 ~]# echo $NAME
mage
[root@CentOS7 ~]# echo $TITLE
wang

Example: variable appended value

[root@CentOS7 ~]# TITLE=CTO
[root@CentOS7 ~]# TITLE+=:wang
[root@CentOS7 ~]# echo $TITLE
CTO:wang

Example: Using variables to implement dynamic commands

[root@CentOS7 ~]# CMD=hostname
[root@CentOS7 ~]# $CMD
CentOS7.magedu.org

 

Displays all variables defined:

set

Delete variables:

unset <name>

Example:

[root@CentOS7 ~]# NAME=mage
[root@CentOS7 ~]# TITLE=ceo
[root@CentOS7 ~]# echo $NAME $TITLE
mage ceo
[root@CentOS7 ~]# unset NAME TITLE
[root@CentOS7 ~]# echo $NAME $TITLE

[root@CentOS7 ~]# 

environment variable

Environment variables:

  • You can make a child process (including a grandchild process) inherit variables from the parent process, but you cannot make the parent process use variables from the child process
  • Once a child process modifies a variable inherited from the parent process, the new value is passed to the grandchild process
  • Usually used only in system configurations, less in scripts
Variable declaration and assignment:
#Declare and assign values
    export name=VALE
    declare -x name=VALE

#Or in two steps
    name=VALUE
    export name
Variable references:
$name
${name}
Display all environment variables:
env
printenv
export
declare -x
Delete variables:
unset name

read-only variable

Read-only variables: can only declare definitions, but cannot be modified or deleted later, and constants. Read-only variables are deleted after the current shell process exits

Declare read-only variables:
readonly name
declare -r name
View read-only variables:
readonly [-p]
declare -r

Location variable

Variables built into the bash shell that invoke parameters passed to the script from the command line in script code

  • Break the command line into individual command words
  • Expand Alias
  • Expand brace declaration {}
  • Expand Wave Statement~
  • Command Replacement $() and ``
  • Divide the command line into command words again
  • Expand File Wildcards*,?, [abc]..
  • Prepare I/O redirection <, >
  • Run Command

Empty all location variables

set --

Exit status code variable

The variable $will be used after the process executes? Save status code related numbers, different values reflect success or failure, $? Value range 0-255

$?Value of 0                #Represents Success
$?Value of 1-255            #On behalf of failure

The user can customize the exit status code in the script using the following commands

exit [n]        #n Range of values: 0-255

Attention:

  • Once an exit command is encountered in a script, the script terminates immediately. The termination exit status depends on the number following the exit command
  • If no exit status code is specified for the script, the exit status code for the entire script depends on the status code of the last command executed in the script

Expand the command line

Expand command line order

Break the command line into individual command words
 Expand Alias
 Declarations Expanded in Braces{}
Expand Wave Character Declaration ~
Command Replacement$()and``
Divide the command line into command words again
 Expand File Wildcards*,?,[abc]Wait
 Get ready I/O Redirection<,>
Run Command

- Prevent Extensions

Backslash(\)Will cause subsequent characters to be interpreted as intended

- Quote to prevent expansion

Single quotation mark('')Prevent all extensions
 Double Quotes("")Extensions can also be prevented, with the following exceptions: $

Variable Extensions

``:Reverse Quotes, Command Replacement
\:Backslash, prohibit single character expansion
!: Exclamation mark, historical command replacement

set command implements script security

-u Displays error message when expanding a variable that is not set, equal to set-o nounset

-e Exits if a command returns a non-zero exit status value (fails), equivalent to set-o errexit

-o option display, turn options on or off

Display options: set -o

Open option: set-o option

Turn off option: set +o option

-x When executing a command, print the command and its parameters, similar to bash-x

Topics: shell