preface

Remember the fear of being dominated by BAT. Writing a BAT script is a lot harder than writing a shell script.

Since you can understand high-level languages like Java JS, it’s easy to understand the shell. Learn the simple syntax, then look at tomcat and Nacos and other familiar application scripts, learn the skills of others, almost get started, for development, enough to use.

Main Contents:

  • Common grammar
  • The operator
  • Special variables
  • For a while, a case, the select, etc

Run your shell online, and use your entire virtual machine for efficiency.

The basic grammar

The parser

When writing scripts, you can use VS Code and install the corresponding plug-in shell-format, which can be used for syntax hints and formatting.

It is important to define the parser for the script when writing it, otherwise strange problems will occur. It is better to give the same to the internal parser of the system.

My system uses bash parsing, which I wrote to define #! /bin/sh Parsing script.

I called the OpenSSL algorithm to calculate the MD5 of the path is not correct anyway. It turns out that the parser definition is different.

#! /bin/shCopy the code
#! /bin/bashCopy the code

Sudo cat /etc/shells You can view the system parser.

Run echo ${SHELL} to view the default parser.

My system is Centos default bash parsing.

/bin/bash echo ${SHELL}Copy the code

annotation

Use # to comment out a line of content.

echo

Echo is often used to print a message to a monitor. We can redirect the content to a file.

MY_CONTENT="12124" \ echo "${MY_CONTENT} Prints the content to the file "> a.txtCopy the code

When typing multi-line commands on the console, we can use \ to link commands.

References to variables using $MY_CONTENT are the same as ${MY_CONTENT}. I’m used to using the latter, safely avoiding errors like $MY_CONTENTaaa, and I’ll have no problem writing ${MY_CONTENT}aaa.

Single quotation marks are different from double quotation marks

MY_CONTENT="12124" \ echo "${MY_CONTENT}Copy the code
${MY_CONTENT} ${MY_CONTENT} ${MY_CONTENT}Copy the code

Single quotes do not substitute variables.

Define variables

It’s easy to define a variable, just follow the Java and JS variable rules directly. Normally, if you do not specify a type, the definition is string data, although there are no single or double quotes. I’m used to defining variables as constants.

A=111Copy the code

Sometimes we need references to variables. The variable A is defined, and B is referenced in A.

#! / bin/bash BB = "zhang qin climbing" AA = "${BB} - mflyyou" echo "${AA} - 456"Copy the code

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

For example, I want to get the current path using PWD and assign A.

#! /bin/bash # or BASE_DIR= 'PWD' BASE_DIR=$(PWD) echoCopy the code

There are also some variables that we want to access in the child process. For example, IF I define BASE_DIR in script A, and I run script B in script A, script B can also access BASE_DIR;

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

Special variables

A special variable is a variable that already has a special meaning that allows us to get some parameters.

variable describe example
$0 Current script name
$n Parameter passed to the script. $1 represents the first parameter
? The process ID of the current shell
$? The exit status or return value of the previous command. 0 indicates normal and the remaining values are abnormal. A value greater than 0 is recommended
$# The number of arguments passed to a script or function

The contents of error.log are as follows.

#! /bin/bash echo "Current script name \$0: $0" echo" the first parameter passed to the script \$1: $1" echo "current shell pid \$\$:?" Echo "return value of last command execution \$? : $?" Echo "number of passes to script \$# : $#" # sleep 6 seconds sleep 6Copy the code
[parallels@centos-7 ~]$sh error.log canshu1 Current script name $0: error.log The first argument passed to the script $1: canshu1 pid of the current shell? : 14952 Return value of last command execution $? : 0 Number of passes to the script $# : 1 [parallels@centos-7 ~]$Copy the code

The operator

File comparison operator

The operator describe
-e Checks whether the file exists, returns true if it does.
-f Returns false if the file is a normal file. Returns true if the file exists.
-d Check if the path is a directory, false if it does not exist. Is a directory and exists returns true.
-r Is the file readable (referring to the read permissions of the user running the test command)
-w Whether the file is writable (referring to the write permission of the user running the test command)
-x Whether the file is executable (referring to the execution permission of the user running the test command)
#; If [! -f "${BASE_DIR}/logs/start.out"]; Then echo file exists "else echo file does not exist" fiCopy the code

Boolean operator

Suppose variable A is 10 and variable B is 20:

The operator instructions For example,
! Non-operation, returns false if the expression is true, and true otherwise. [ ! false ]

Returns true.
-o Or, returns true if one of the expressions is true. [ $a -lt 20 -o $b -gt 100 ]

Returns true.
-a And, returns true if both expressions are true. [ $a -lt 20 -a $b -gt 100 ]

Returns false.

Logical operator

The following describes the Shell’s logical operators, used by [[]]. Suppose variable A is 10 and variable B is 20:

The operator instructions For example,
&& The logic of the AND [[ $a -lt 100 && $b -gt 100 ]]

Returns false
|| The logic of the OR [[ $a -lt 100 || $b -gt 100 ]]

Returns true
#! / bin/bash a = b = 10 20 if [[$100 & a - lt & $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" fiCopy the code
Return false Returns trueCopy the code

String comparison operator

The following table lists the common string operators, assuming variable A is “ABC” and variable B is “efg” :

The operator instructions For example,
= Checks if two strings are equal. Equality returns true. [ ${a} = ${b} ]

Returns false.
! = Checks if two strings are equal. Returns true if they are not. [ ${a} != ${b} ]

Returns true.
< <, in ASCII order. Note that the “<” character needs to be escaped in the [] structure If [[” ${a}” < “${b}”]]

If [” ${a}” \< “${b}”]
> >, in ASCII order. Note that the “>” characters need to be escaped in the [] structure. If [[” ${a}” > “${b}”]]

If [” ${a}” > “${b}”]
-z Checks if the string length is 0, and returns true for 0. [-z “${a}”]

Returns false.
-n Checks if the string length is 0, and returns true if it is not 0. [ -n “$a” ]

Returns true.
#! If ["${a}x" == "${b}x"]; Then the echo "${a} = = ${b} : a equals b" else echo "${a} = = ${b} : a is not equal to b" fi if [" ${a} "/ >" ${b} "]. Then echo 'greater than' else echo "less than" fi if [[" ${a} ">" ${b} "]]. Then echo '>' else echo '<' fiCopy the code

Numeric comparison operator

The following comparators can only compare numbers or numeric strings. Comparisons of non-numbers report errors.

Comparison operator describe example
-eq Is equal to the if [ 3 -eq "3" ]To true
-ne Is not equal to if [ "$a" -ne "$b" ]
-gt Is 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 operator

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

Operational operator describe example
+ A plus sign echo $((2+2))
A minus sign
/ devide
* Multiplication sign
** exponentiation
% modulus

Define a function

variable describe example
$0 Current script name
$n Parameter passed to the script. $1 represents the first parameter
? The process ID of the current shell
$? The exit status or return value of the previous command. 0 indicates normal and the remaining values are abnormal. A value greater than 0 is recommended
$# The number of arguments passed to a script or function
} f2 aaa # return f2 aaa to code code=$(($?)) { ${code} ${code}Copy the code

if

#; If [! -f "${BASE_DIR}/logs/start.out"]; Then echo file exists "else echo file does not exist" fiCopy the code

for

The syntax is relatively simple and there is nothing to say.

strs="Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto" for planet in ${strs}; Do echo ${planet} # Each planet is printed on a single line. DoneCopy the code

while

The syntax is relatively simple and there is nothing to say.

#! /bin/bash count=1 while [ ${count} -le 5 ]; Do echo "Loop # ${count}" # count=$((${count} + 1)) # ((count++)) doneCopy the code

case

Similar to switch syntax in Java.

#! / bin/bash fn () {case "$1" in matching a or c # "a" | "c") echo "input parameters for $1";; "B ") echo" 2 = 2; Echo "input other"; esac } fn a1Copy the code

select

Select is useful because sometimes we need the user to select a command to execute,

#! /bin/bash Operations=("start" "stop" "restart" ${Operations[@]}; Do case ${operation} in "start") echo "Start" break ;; "Stop ") echo" Run the stop operation. break ;; "Restart ") echo" Perform the restart operation." break ;; *) echo "Input error, please re-enter..." ;; esac doneCopy the code

After running the script above, and then you type 1, the start operation is performed. Very convenient, no user input parameters.

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

Start and close Java service scripts

Start the

Reference is made to the nacOS script directory and authoring.

#! JAR_NAME="proximab-server" # JAVA_OPT=" -server-xms1g-xmx1g-xmn512m - XX: MetaspaceSize = 256 m - XX: MaxMetaspaceSize = 512 m "# set related JAVA_OPT gc log =" ${JAVA_OPT} - XX: + HeapDumpOnOutOfMemoryError If [-z "${JAVA_HOME}"]; if [-z "${JAVA_HOME}"]; if [-z "${JAVA_HOME}"]; then echo "please set JAVA_HOME"; exit 1; Export Java ="${JAVA_HOME}/bin/ Java "export BASE_DIR= 'CD $(dirName $0)/.. ; PWD ` # set configuration file location, and define your own configuration file location DEFAULT_SEARCH_LOCATIONS = "classpath: /, the classpath: / config/file:. /, file:. / config/" CUSTOM_SEARCH_LOCATIONS=${DEFAULT_SEARCH_LOCATIONS},file:${BASE_DIR}/conf/ # 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" -- logging. The log - path = ${BASE_DIR} / logs "# project log position if [! - d" ${BASE_DIR} / logs "]. Then mkdir ${BASE_DIR}/logs fi # if [! -f "${BASE_DIR}/logs/start.out"]; Echo "${Java} ${JAVA_OPT} "then touch "${BASE_DIR}/logs/start.out" ${BASE_DIR}/lib/${JAR_NAME}" > ${BASE_DIR}/logs/start.out 2>&1 & # ${JAVA_OPT} >> ${BASE_DIR}/logs/start.out 2>&1 & echo "${JAR_NAME} is starting, you can check the ${BASE_DIR}/logs/start.out"Copy the code

Shut down

#! JAR_NAME="proximab-server" # # 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 )"Copy the code

This article was created by Zhang Panqin’s blog. It can be reproduced and quoted freely, but the author must be signed and indicate the source of the article.

If reprinted to wechat official account, please add the author’s official qr code at the end of the article. Wechat official account name: Mflyyou