Linux-Packaged Tutorial Club Series-shell

Keywords: Front-end shell Java less CentOS

Preface

Remember the fear of being dominated by bat.It's really hard to write bat scripts than shell scripts.

Now that you understand these advanced languages, such as java js, it's easy to understand shell s.Learn simple grammar, look at scripts in familiar applications like tomcat and nacos, and learn other people's skills. It's about getting started. It's enough for development.

Main Contents:

  • Common Syntax
  • operator
  • Special variables
  • for,while,case,select, etc.

Run shell Online For efficiency, use your entire virtual machine.

Basic Grammar

Parser

When writing scripts, you can use vs code to install the appropriate plug-in shell-format for syntax prompting and formatting.

When writing a script, be sure to define the parser for the script, otherwise there will be strange problems.It's best to give the parser inside the system the same.

My system uses bash parsing, and I have written a definition #!/bin/sh parsing script.

I call the openssl algorithm to calculate the md5 of the path is never correct.The last thing I found was that the parser definitions were different.

#!/bin/sh
#!/bin/bash

Sudo cat/etc/shells can view the system's parser.

Run echo ${SHELL} to see the system default parser.

My system is the Centos default bash resolution.

# Print out/bin/bash
echo ${SHELL}

Notes

Use # to comment on a line.

echo

echo is often used to print a paragraph to the display.We can save the content to a file by redirecting it.

MY_CONTENT="12124" \
echo "${MY_CONTENT}Print content to file" > a.txt

When we enter a multiline command in the console, we can use \ to link commands.

The references to variables using $MY_CONTENT and ${MY_CONTENT} are the same.I am accustomed to the latter, safe, and avoid errors like $MY_CONTENT aaa, so I can write ${MY_CONTENT}aaa without any problems.

Difference between single quotation mark and double quotation mark

MY_CONTENT="12124" \
echo "The printout is: ${MY_CONTENT}" 

# Print content is: 12124
MY_CONTENT="12124" \
echo 'The printout is: ${MY_CONTENT}'

# Print: ${MY_CONTENT}

Single quotation marks do not replace variables.</font>

Define Variables

Defining variables is easy, just follow the variable rules of java and js.Typically, definitions are string-type data, although there are no single or double quotes.I'm used to defining variables as constants.

A=111

Sometimes we need a reference to a variable.Variable A is defined and B is referenced in A.

#!/bin/bash
BB="Zhang Panqin"
AA="${BB}-mflyyou"
echo "${AA}-456"

Sometimes you want to assign the result of a command to a variable.

For example, I want to use pwd to get the current path and assign A.

#!/bin/bash

# Or BASE_DIR=`pwd`
BASE_DIR=$(pwd)
echo "The current path is: ${BASE_DIR}"

There are also variables that we want to make accessible in the child process.For example, BASE_DIR that I defined in a script and b script that I run in a can also access BASE_DIR;

export BASE_DIR=`cd $(dirname $0)/..; pwd`

Special variables

Special variables are variables that already have special meaning, so we can get some parameters.

variable describe Example
$0 Current script name
$n The parameter passed to the script, $1 for the first parameter
$$ Process id of current shell
$? The exit status or function return value of the last command, 0, indicates normal, and the remaining values are abnormal.Suggested greater than 0 indicates an exception
$# Number of parameters passed to a script or function

The following is in error.log.

#!/bin/bash

echo "Current script name \$0: $0"

echo "The first parameter passed to the script \$1:  $1"

echo "current shell Of pid \$\$:  $$"

echo "Return value from last command execution \$?: $?"

echo "Number of Passes to Script \$#: $#"

# Sleep for 6 seconds
sleep 6
[parallels@centos-7 ~]$ sh error.log canshu1
 Current script name $0: error.log
 The first parameter passed to the script $1:canshu1
 Current shell pid $$:14952
 Return value from last command execution $?:0
 Number of scripts passed to $#:1
[parallels@centos-7 ~]$

operator

File Comparison Operator

Operator describe
-e Determines whether the file exists and returns true.
-f Determines if the file is a normal file and does not return false.File existence returns true.
-d Determines if the path is a directory and does not return false.Is a directory and exists returns true.
-r Is the file readable (refers to the user's read permissions to run this test command)
-w Is the file writable (referring to the write permissions of the user running this test command)
-x Is the file executable (refers to the executable rights of the user running the test command)
# A space is required between the
if [ ! -f "${BASE_DIR}/logs/start.out" ]; then
    echo "File Exists"
else
    echo "file does not exist"
fi

Boolean Operator

Assume variable a is 10 and variable b is 20:

operator Explain Give an example
! Not an operation, the expression true returns false, otherwise it returns true. [! False] <br>Returns true.
-o Or, an expression that is true returns true. [$a-lt 20-o $b-gt 100] <br/>Returns true.
-a And operation, both expressions are true to return true. [$a-lt 20-a $b-gt 100] <br/>Returns false.

Logical operators

The following describes Shell's logical operators, [[]] use.Assume variable a is 10 and variable b is 20:

operator Explain Give an example
&& Logical ADD [[$a-lt 100 & & &$b-gt 100]] <br/>Returns false
|| Logical OR [[$a-lt 100 || $b-gt 100]] <br/>Returns true
#!/bin/bash
a=10
b=20

if [[ $a -lt 100 && $b -gt 100 ]]
then
   echo "Return true"
else
   echo "Return false"
fi

if [[ $a -lt 100 || $b -gt 100 ]]
then
   echo "Return true"
else
   echo "Return false"
fi
Return false
 Return true

String comparison operator

The following table lists common string operators, assuming variable a is "abc" and variable b is "efg":

operator Explain Give an example
= Detects whether two strings are equal and returns true for equality. [${a} = ${b}] <br/>Returns false.
!= Detects whether two strings are equal, and returns true if they are not equal. [${a}!= ${b}] <br/>Returns true.
< Less than, in ASCII character order, note that the'<'character needs to be escaped in the [] structure if [[ "${a}" < "${b}" ]] <br>if [ "${a}" \< "${b}" ]
> Greater than, in ASCII character order, note that the'>'character needs to be escaped in the [] structure. if [[ "${a}" > "​${b}" ]]<br>if [ "​${a}" > "${b}" ]
-z Detects whether the string length is 0 and returns true for 0. [-z'${a}'] <br/> returns false.
-n Detects whether the string length is 0, does not return true for 0. [-n'$a'] <br/>Returns true.
#!/bin/bash
a=e1
b=e2
# Mix one character for safer comparison
if [ "${a}x" == "${b}x" ]; then
   echo "${a} == ${b}: a Be equal to b"
else
   echo "${a} == ${b}: a Not equal to b"
fi

if [ "${a}" \> "${b}" ]; then
echo 'greater than'
else
echo "less than"
fi

if [[ "${a}" > "${b}" ]]; then
echo 'greater than'
else
echo "less than"
fi

Numeric comparison operator

The following comparators can only compare numbers or numeric strings, which can cause errors when compared with non-numbers.

Comparison operator describe Example
-eq Be equal to If [3-eq'3'] is true
-ne Not equal to if [ "$a" -ne "$b" ]
-gt greater than if [ "$a" -gt "$b" ]
-ge Greater than or equal to if [ "$a" -ge "$b" ]
-lt less than if [ "$a" -lt "$b" ]
-le Less than or equal to if [ "$a" -le "$b" ]

Arithmetic Operators

$(()) can be used for numerical operations.

Operator describe Example
+ Plus echo $((2+2))
- Minus sign
/ Division sign
* Multiplication sign
** Exponentiation
% Modulus

Define Functions

variable describe Example
$0 Current script name
$n The parameter passed to the script, $1 for the first parameter
$$ Process id of current shell
$? The exit status or function return value of the last command, 0, indicates normal, and the remaining values are abnormal.Suggested greater than 0 indicates an exception
$# Number of parameters passed to a script or function
f2() {
    # Declare local variables
    local loc_val=23
    echo "The first value passed to the function is: $1"
    return "22"
}
f2 aaa
# Assign code to the return result of the last command f2 aaa
code=$(($?))
echo "implement f2 The return value of ${code}"

if

# A space is required between the
if [ ! -f "${BASE_DIR}/logs/start.out" ]; then
    echo "File Exists"
else
    echo "file does not exist"
fi

for

There is nothing to say about the simpler grammar.

strs="Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto"
for planet in ${strs}; do
    echo ${planet} # Each planet is printed on a separate line.
done

while

There is nothing to say about the simpler grammar.

#!/bin/bash
count=1
while [ ${count} -le 5 ];
do
	echo "Loop # ${count}"
	# count increases by itself
	count=$(( ${count} + 1 ))
	# ((count++))
done

case

Similar to switch syntax in java.

#!/bin/bash
fn() {
    case "$1" in
    # Match a or c
    "a" | "c")
        echo "The input parameter is $1 "
        ;;

    "b")
        echo "Input parameter 2 is 2 "
        ;;

        # Match other
    *)
        echo "Enter another"
        ;;
    esac
}
fn a1

select

Selectect is also useful because sometimes we need users to choose the commands they need to execute.

#!/bin/bash
Operations=("start" "stop" "restart")
# Enter prompt
PS3="Please input the number of operation :"
select operation in ${Operations[@]}; do
    case ${operation} in
    "start")
        echo "implement start Operation."
        break
        ;;
    "stop")
        echo "implement stop Operation."
        break
        ;;
    "restart")
        echo "implement restart Operation."
        break
        ;;
    *)
        echo "Input error, please re-enter..."
        ;;
    esac
done

After running the above script, you type 1, which performs the start operation.Very convenient, no user input parameters are required.

1) start
2) stop
3) restart
Please input the number of operation :

Start and close java service scripts

start-up

Reference nacos script directory and writing.

#!/bin/sh

# Setting the jar package for springboot startup
JAR_NAME="proximab-server"


# Setting jvm configuration information
JAVA_OPT="-server -Xms1g -Xmx1g -Xmn512m -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m"

# Set gc log correlation
JAVA_OPT="${JAVA_OPT} -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${BASE_DIR}/logs/java_heapdump.hprof"

#
# Just consider modifying the above parameters
#

# Determine whether to configure JAVA_HOME
if [ -z "${JAVA_HOME}" ]; then
    echo "please set JAVA_HOME";
    exit 1;
fi

# Set the java path to execute
export JAVA="${JAVA_HOME}/bin/java"

# Set the root path of the project
export BASE_DIR=`cd $(dirname $0)/..; pwd`

# Set profile location and customize your own profile location
DEFAULT_SEARCH_LOCATIONS="classpath:/,classpath:/config/,file:./,file:./config/"
CUSTOM_SEARCH_LOCATIONS=${DEFAULT_SEARCH_LOCATIONS},file:${BASE_DIR}/conf/

# Set Startup Profile
JAVA_OPT="-jar ${JAVA_OPT} ${BASE_DIR}/lib/${JAR_NAME}.jar --spring.config.location=${CUSTOM_SEARCH_LOCATIONS}"
JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/logback-spring.xml"
# Configuration Log File Generation Location
JAVA_OPT="${JAVA_OPT} --logging.log-path=${BASE_DIR}/logs"


# Project log location
if [ ! -d "${BASE_DIR}/logs" ]; then
  mkdir ${BASE_DIR}/logs
fi

# Output startup log at startup
if [ ! -f "${BASE_DIR}/logs/start.out" ]; then
  touch "${BASE_DIR}/logs/start.out"
fi

# Print boot java-related configuration information to the log file
echo "${JAVA} ${JAVA_OPT} ${BASE_DIR}/lib/${JAR_NAME}" > ${BASE_DIR}/logs/start.out 2>&1 &

# Redirect error and normal input logs to start.out
nohup ${JAVA} ${JAVA_OPT} >> ${BASE_DIR}/logs/start.out 2>&1 &

echo "${JAR_NAME} is starting,you can check the ${BASE_DIR}/logs/start.out"

Close

#!/bin/sh

# Set jar name
JAR_NAME="proximab-server"


#
# Just consider modifying the above parameters
#


# Set the root path of the project
export BASE_DIR=`cd $(dirname $0)/..; pwd`

PID=`ps -ef | grep -i "${JAR_NAME}.jar" | grep java | grep -v grep | awk '{print $2}'`

if [ -z "$PID" ] ; then
        echo "No ${JAR_NAME} running."
        exit 1;
fi

echo "The ${JAR_NAME} is running ,PID is (${PID}) ..."

kill ${PID}

if [ $? != 0 ]; then
    echo "kill ${JAR_NAME} fail"
    exit 1;
fi
echo "kill ${JAR_NAME} is OK, PID (${PID} shutdown )"

This article is written by Zhang Panqin's Blog A literary creation.It can be freely reproduced and quoted, but with the signature of the author and the citation of the article.

If you upload it to the WeChat Public Number, add the Author Public Number 2-D at the end of the article.WeChat Public Number Name: Mflyyou

Posted by mpower on Sat, 21 Mar 2020 22:14:33 -0700