How to start shell script programming quickly

Time:2021-5-4

Before Linux shell script programming, there has been no systematic study. When writing shell script, you always need to check all kinds of syntax. This article uses the dimension of programming language to systematically learn shell script programming.

Shell

Linux shell is an application program that interacts with Linux system, through which we can operate kernel services of Linux system.

implement$cat /etc/shellsYou can see the shell interpreter now available in the system

# List of acceptable shells for chpass(1).
# Ftpd will not allow users to connect who are not using
# one of these shells.

/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh
/usr/local/bin/zsh

In modern Linux system/bin/shHas been/bin/bashAs the default shell of Linux

input$echo $SHELLYou can see the shell of the current system

Shell script

Shell script is a script program written for shell. By shell, we usually refer to shell scripts.

Shell variable

Shell script is a weakly typed scripting language, so it is not necessary to define the variable type in advance.

Possible pits:

  1. Assignment variable cannot have dollar sign($)
  2. Assignment statement equal sign(=)There can be no spaces left or right

Variable definition

#!/bin/bash

#Direct assignment
name="cizel"

#Statement assignment
for file in `ls /etc`

Variable usage

#!/bin/bash

#Define variable name
name="cizel"

#Use the dollar ($) symbol
echo $name

#Use the dollar ($) symbol和括号结合,常用于字符串拼接
echo ${name}

or

#!/bin/bash

#Advanced usage

#Default value: if the variable is not declared, use the default value ${var = Default}
echo ${name="ok"}
# output: ok

#Default value: if the variable is not declared or is an empty string, use the default value ${var: = Default}
name=""
echo ${name:="ok"}
# output: ok

Shell number operation

The number operation in shell can use$((num1 + num2))For example:

Possible pits:

  1. The variable in shell is string by default, usingresult=1+2;echo $resultThe output will be1+2
  2. The two variables of a numeric operation must benumberperhapsNumeric stringOtherwise, it will report an error
#!/bin/bash

a=2
b="3"

echo (($a + $b))
# output: 5

echo (($a - $b))
# output: -1

echo (($a * $b))
# output: 6

echo (($a / $b))
# output: 0

#Modulo / complement
echo $(($a % $b))
# output: 1

#Power
echo $(($a ** $b))
# output: 8

#Complex operation
echo $(($a + ($a * $b)))
# output: 8

Shell string

Shell string is the same as PHP string, which is divided intoSingle quotation stringandDouble quotation string

String definition

#!/bin/bash

$name="cizel"
#Variables and symbols in single quotation marks are not parsed
echo 'my name is ${name}'
# output: my name is ${name}

#Variables and symbols in double quotes are parsed
echo 'my name is ${name}'
# output: my name is $shizhen

String connection

#!/bin/bash

name="cizel"
echo $name $name
# output:cizel cizel

String length

#!/bin/bash

name="cizel"
echo ${#name}
# output: 5

String interception

#!/bin/bash

name="my name is cizel"

echo ${name:2}
# output: name is cizel

echo ${name:2:5}
# output: name

String deletion

${variable name # substring regular expression} from stringstartStart to equipsubstring, delete the expression on the match.

${variable name% substring regular expression} from stringendingStart to equipsubstring, delete the expression on the match.

#!/bin/bash

test="/home/work/.vimrc"

echo ${test#/home}
# output: /work/.vimrc

or

#!/bin/bash

#Advanced usage

test="/home/work/.vimrc"

#Quick access to file name
echo ${test##*/}
# output: .vimrc

#Quick access path
echo ${test%/*}
# output: /home/work

String replacement

Using the built-in string replacement, it is better thanawk, sed, exprBetter performance,

${variable / find / replace value} a ‘/’ means to replace the first and ‘/ /’ means to replace all.

#!/bin/bash

test="/home/work/.vimrc"

echo ${test/.vimrc/.zshrc}
# output: /home/work/.zshrc

echo ${test/w*k/cizel}
# output: /home/cizel/.vimrc

Shell logic operation

In shell, usetestTo make a logical judgment. There are many differences from other programming languages, if true return0, false return1.

Possible pits:

  1. Logical judgment result true return0, false return1
  2. use-gt, -lt, -ge, -le, -ne, -eqreplace>, <, >=, <=, !=, =Do numerical comparison
  3. Use of and or not operators-a, -o, !replace& | !

Numerical comparison

The operators of numerical comparison are similar to those in assembly language. Five common numerical comparisons are as follows:

Symbol English explanation Chinese explanation
-gt greater than greater than
-lt less than less than
-ge greater equal Greater than or equal to
-le less equal Less than or equal to
-ne not equal Not equal to
-eq equal be equal to
#!/bin/bash

#Greater than
test 3 -gt 2; echo $?
# output: 0

#Less than
test 3 -lt 2; echo $?
# output: 1

#Greater than等于
test 3 -ge 2; echo $?
# output: 0

#Less than等于
test 3 -le 2; echo $?
# output: 1

#Not equal to
test 3 -ne 2; echo $?
# output: 0

#Equal to
test 3 -eq 2; echo $?
# output: 1

string comparison

The operators of string comparison are as follows:

Symbol explain
= String equals
!= String inequality
-z Determine whether the string length is zero
-n Determine whether the string length is greater than zero
#!/bin/bash

#String equals
test "my name is cizel" = "my name is cizel"; echo $?
# output: 0

#String inequality
test "my name is cizel" = "my name is cz"; echo $?
# output: 1

#String length judgment
test -z "my name is cizel"; echo $?
# output: 1
test -n "my name is cizel"; echo $?
# output: 0

Document comparison

Symbol explain
-e Judge whether the file is correctexistence.
-d Judge whether the file iscatalogue.
-f Judge whether the file isGeneral documents.
-L Judge whether the file isSymbolic links.
-r Judge whether the file is correctreadable.
-w Judge whether the file is correctWritable.
-x Judge whether the file is correctExecutable.
#!/bin/bash

ls -l

#The current directory includes the following files, lib folder, run.sh file, SH symbolic link, and current role: work
# drwxr-xr-x 1 work work 4096 Jun 28  2018 lib
# -rwxr-xr-x 1 work work 2364 Jul  7  2018 run.sh
# lrwxrwxrwx 1 root root  4 May 26  2014 sh -> bash

#Judge whether the file exists
test -e run.sh; echo $?
# output: 0

#Determine if the directory exists
test -d lib; echo $?
# output: 0

#Judge whether the file is regular or not
test -f run.sh; echo $?
# output: 0

#Determine whether the file is a symbolic link
test -L sh; echo $?
# output: 0

#Determine whether the file is a symbolic link
test -L sh; echo $?
# output: 0

#Judge whether the file is readable / writable / executable (current role, work, permission RWX, readable / writable / executable)
test -r run.sh; echo $?
# output: 0
test -w run.sh; echo $?
# output: 0
test -x run.sh; echo $?
# output: 0

Logical connection

Like other programming languages, shell also has and or not operators. It is used to connect logic judgment conditions to form compound logic judgment.

Symbol English explanation Chinese explanation
-a and And
-o or or
! wrong
#!/bin/bash

#And
test "1" = "1" -a "1" = "2"; echo $?
# output: 1

#Or
test "1" = "1" -o "1" = "2"; echo $?
# output: 0

#Not
test ! "1" = "2"; echo $?
# output: 0

Shell selection structure

The selection statements in shell are similar to other programming languages, and support common conditional selection methods such as if, if else, if elif, if elif else and case ESAC

Possible pits:

  1. Left bracket of if condition([)There must be a space after and before the right bracket(])There must be a space. if [SpaceexpressionSpace]
  2. If, elif need to be added afterthenThen add the statement

If selection

#!/bin/bash

var=`uname -s`

if [ $var = "Linux" ]; then
  echo "Linux System"
fi

If else selection

#!/bin/bash

var=`uname -s`

if [ $var = "Linux" ]; then
  echo "Linux System"
else
  echo "Other System"
fi

If elif selection

#!/bin/bash

var=`uname -s`

if [ $var = "Linux" ]; then
  echo "Linux System"
elif [ $var = "FreeBSD" ]; then
  echo "FreeBSD System"
fi

If elif else selection

#!/bin/bash

var=`uname -s`

if [ $var = "Linux" ]; then
  echo "Linux System"
elif [ $var = "FreeBSD" ]; then
  echo "FreeBSD System"
else
  echo "Other System"
fi

Case ESAC selection

Case ESAC is similar to the commonly used switch case, which can be used to choose food compared with if elif else

#!/bin/bash

var=`uname -s`

case $var in
"Linux")
  echo "Linux System"
  ;;
"FreeBSD")
  echo "FreeBSD System"
  ;;
*)
  echo "Other System"
  ;;
esac

Shell loop structure

For loop

Common writing method similar to C language

#!/bin/bash

#To print 1-10, double brackets must be used to transfer the symbol
for ((i=1; i<=10; i++)); do
  echo $i
done

The method of in(Commonly used)

#!/bin/bash

for i in {1..10}; do
  echo $i
done

While loop

#!/bin/bash

count=1
while [ $count -lt 3 ]; do
  echo $count
  count=$((count + 1))
done

Until loop

Stop the cycle until the condition is true

#!/bin/bash

count=1
until [ $count -eq 3 ]; do
  echo $count
  count=$((count + 1))
done

Shell function

Shell function, using $1.. $n to receive parameters

#!/bin/bash

my_func() {
  echo "my function"
  echo "params 1: $1"
  echo "params 2: $2"
  echo "params 3: $3"
}

my_func 1 2 3

Shell load script

Used in shellsourceCommand to load other files into the current shell script

# echo.sh

echo() {
  command printf %s\n "$*" 2>/dev/null
}
#!/bin/bash

source echo.sh

echo 123

Related links

Original address:https://www.cizel.cn/post/she…

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]