Variables and Environment Variables

    Scripting languages ​​often do not need to declare the type of a variable before using it. In Bash, the value of every variable is a string, with or without quotes. There are also variables that are used by the shell environment and the operating system environment to store special values. These variables are called environment variables.

    To view all environment variables associated with a terminal, use the env command. For each process, to view the environment variables associated with the process running, use the cat /proc/$PID/environ command, where $PID should be replaced with the PID value of a process. For example, suppose there is an application called gedit running. We can use the pgrep gedit command to get its process ID. If it is 12501, then the command just now should be cat /proc/12501/environ, and the output is some name-value pairs. The name-value pairs are passed through the null character ( \0) delimited. If you could replace \0 with \n, the result would be line-by-line name-value pairs. The final command is:

cat /proc/12501/about | tr '\0' '\n'

    var=value, if value contains space characters, you need to enclose the value in quotation marks, both single and double quotation marks are fine. Note that var = value and

var=value is different. The former is an equality operation, while the latter is an assignment operation. To print the value of a variable, prefix the variable name with a $, so echo $var or echo ${var}

    We can use variable values ​​in double quotes in printf and echo:

#!/bin/bash

#Filename :variables.sh

fruit=apple

count=5

echo "We have $count ${fruit}(s)"

The output is: We have 5 apple(s)

    Environment variables are not defined in the current process, but are received from the parent process. For example, HTTP_PROXY is an environment variable that defines which proxy server should be used for an Internet connection. The export command is used to set env variables.

    Typically, $PATH is defined in /etc/environment or /etc/profile or ~/.bashrc. Some well-known environment variables include HOME, PWD, USER, SHELL, and more.

 

Get the length of a string: length=${#var}, for example:

$ var = 12345678901234567890 $

echo $ {# var

20

 

Get current SHELL: echo $SHELL or echo $0

 

Checking for super user: UID is an important environment variable that can be used to check whether the current script is being executed as root or as a normal user. If the root user is the root user, the value of this variable is 0.

if [ $UID -ne 0 ]; then

    echo Non root user. Please run as root.

else

    echo Root user

be

 

Customize the shell prompt: Via the PS1 environment variable. The default prompt text for the shell is defined in ~/.bashrc.

$ cat ~/.bashrc | grep PS1 to know how the prompt text is defined.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327034281&siteId=291194637