Linux Shell script programming has not been systematic to learn, when writing Shell scripts always need to check various syntax. This article systematically studies Shell script programming from the dimension of programming language.

Shell

The Linux Shell is an application program that interacts with the Linux system. We can operate the kernel services of the Linux system through this program.

Run $cat /etc/shells to see the Shell interpreter now available on 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
Copy the code

In modern Linux systems /bin/sh has been replaced by /bin/bash as the default Linux Shell.

Enter $echo $SHELL to view the SHELL of the current system.

A Shell script

A Shell Script is a Script program written for the Shell. When we say Shell, we usually mean Shell scripts.

Shell variables

Shell scripting is a weakly typed scripting language and does not need to define variable types in advance.

Possible pits:

  1. Assignment variables cannot have dollar signs ($)
  2. Assignment statement equal sign (=) no Spaces left or right

Variable definitions

#! /bin/bash
# Direct assignment
name="cizel"

# statement assignment
for file in `ls /etc`
Copy the code

Variable used

#! /bin/bash
# define variable name
name="cizel"

# use the dollar ($) sign
echo $name

# uses the dollar ($) symbol combined with parentheses, often used for string concatenation
echo ${name}
Copy the code

or

#! /bin/bash
# Advanced usage

${var=DEFAULT} ${var=DEFAULT}
echo ${name="ok"}
# output: ok

${var:=DEFAULT} ${var:=DEFAULT} ${var:=DEFAULT}
name=""
echo ${name:="ok"}
# output: ok
Copy the code

Shell numeric operation

$((num1 + num2))); for example:

Possible pits:

  1. Variables in the Shell are strings by defaultresult=1+2; echo $result, the output will be1 + 2
  2. The two variables of the numerical operation must bedigitalorNumeric stringOtherwise, an error will be reported
#! /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

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

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

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

Shell string

Shell strings are the same as PHP strings, with single and double quoted strings

String definition

#! /bin/bash
$name="cizel"
Variables and symbols in single quotes 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
Copy the code

String conjunction

#! /bin/bash
name="cizel"
echo $name $name
# output:cizel cizel
Copy the code

String length

#! /bin/bash
name="cizel"
echo ${#name}
# output: 5
Copy the code

String interception

#! /bin/bash
name="my name is cizel"

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

echo ${name:2:5}
# output: name
Copy the code

String deletion

${variable name # subString regular expression} is equipped with substring at the beginning of the string, and the expression matching is deleted.

${variable name % SUBString regular expression} is equipped with substring from the end of the string to delete matching expressions.

#! /bin/bash
test="/home/work/.vimrc"

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

or

#! /bin/bash
# Advanced usage

test="/home/work/.vimrc"

Get the file name quickly
echo ${test##*/}
# output: .vimrc

Get the path quickly
echo ${test%/*}
# output: /home/work
Copy the code

String substitution

Use the built-in string substitution to perform better than AWK, sed, expR,

${variable/find/replace value} a “/” to replace the first, “//” 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
Copy the code

Shell logic operation

In the Shell, test is used for logical judgment. Unlike many other programming languages, it returns 0 if true and 1 if false.

Possible pits:

  1. Logical judgment result returns true0, false return1
  2. use-gt.-lt.-ge.-le.-ne.-eqreplace>.<.> =.< =.! =.=Do numerical comparisons
  3. Used with and or not operators-a.-o.!replace& | !

The numerical comparison

The operators for numerical comparisons are similar to those in assembly language. The five common numerical comparisons are as follows:

symbol English interpretation Chinese interpretation
-gt greater than Is 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 Is not equal to
-eq equal Is equal to the
#! /bin/bash
# is greater than the
test 3 -gt 2; echo $?
# output: 0

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

# greater than or equal to
test 3 -ge 2; echo $?
# output: 0

Less than or equal to
test 3 -le 2; echo $?
# output: 1

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

# is equal to the
test 3 -eq 2; echo $?
# output: 1
Copy the code

String comparison

The string comparison operators are as follows:

symbol explain
= String is equal to
! = String inequality
-z Checks whether the string length is zero
-n Checks 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
Copy the code

The file is

symbol explain
-e Determine whether the fileThere are.
-d Check whether the file isdirectory.
-f Check whether the file isRegular file.
-L Check whether the file isA symbolic link.
-r Determine whether the fileCan be read.
-w Determine whether the fileCan write.
-x Determine whether the fileThe executable.
#! /bin/bash
ls -l

The current directory contains the following files: lib folder, run.sh file, sh symbolic link, 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

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

Check whether the directory exists
test -d lib; echo $?
# output: 0

Check whether the file is a regular file
test -f run.sh; echo $?
# output: 0

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

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

# check whether the file is readable/writable/executable.
test -r run.sh; echo $?
# output: 0
test -w run.sh; echo $?
# output: 0
test -x run.sh; echo $?
# output: 0
Copy the code

Logical connection

Like other programming languages, the Shell has and or not operators. It is used to connect logical judgment conditions and form compound logical judgment.

symbol English interpretation Chinese interpretation
-a and with
-o or or
! non
#! /bin/bash
# and
test "1" = "1" -a "1" = "2"; echo $?
# output: 1

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

# the
test ! "1" = "2"; echo $?
# output: 0
Copy the code

Shell selection structure

Select statements in the Shell are similar to other programming languages in that they support if, if-else, if-elif, if-elif-else, and case-esac criteria

Possible pits:

  1. The opening parenthesis of the if condition ([) must be followed by a space, and before the closing parenthesis (]) must have a space. if [The blank spaceexpressionThe blank space]
  2. If, elifthenAnd then add the statement

If choose

#! /bin/bash
var=`uname -s`

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

If – else option

#! /bin/bash
var=`uname -s`

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

If – elif choice

#! /bin/bash
var=`uname -s`

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

If elif – else option

#! /bin/bash
var=`uname -s`

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

Case-shiller esac choice

Case-esac is similar to the common switch-case. You can choose to eat it 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
Copy the code

Shell loop structure

The for loop

Common c language similar writing method

#! /bin/bash
# Print 1-10, double parentheses must be used to make the symbol transfer
for ((i=1; i<=10; i++)); do
  echo $i
done
Copy the code

Methods of in (common)

#! /bin/bash
for i in{1.. 10};do
  echo $i
done
Copy the code

The while loop

#! /bin/bash
count=1
while [ $count -lt3];do
  echo $count
  count=$((count + 1))
done
Copy the code

Until cycle

Stop the loop until the condition is true

#! /bin/bash
count=1
until [ $count -eq3];do
  echo $count
  count=$((count + 1))
done
Copy the code

The Shell function

Shell function, usingN to receive parameters

#! /bin/bash
my_func() {
  echo "my function"
  echo "params 1: The $1"
  echo "params 2: $2"
  echo "params 3: $3"
}

my_func 1 2 3
Copy the code

Shell loading script

Use the source command in the Shell to load additional files into the current Shell script

# echo.sh

echo() {
  command printf %s\\n "$*" 2>/dev/null
}
Copy the code
#! /bin/bash
source echo.sh

echo 123
Copy the code

A link to the

  • Linux several common Shell
  • 30 minutes introduction to Shell scripting
  • Linux shell string manipulation (length, find, replace) details
  • Comparison of Linux shell regular expressions (BREs,EREs,PREs)
  • Shell Style Guide