【Linux】Shell

Posted by 西维蜀黍 on 2020-04-26, Last Modified on 2022-04-03

判断 - if

#!/bin/bash
# Basic if statement
if [ $1 -gt 100 ]; then
  echo Hey that\'s a large number.
  pwd
fi

if-else

#!/bin/sh

a=10
b=20

if [ $a == $b ]; then
  echo "a is equal to b"
elif [ $a -gt $b ]; then
  echo "a is greater than b"
elif [ $a -lt $b ]; then
  echo "a is less than b"
else
  echo "None of the condition met"
fi

&& and ||

for g in 1 2 3
do
    for c in 123 456 789
    do
        if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
        then echo "g = $g; c = $c; true"
        else echo "g = $g; c = $c; false"
        fi
    done
done

循环

while

#!/bin/sh

a=0
while [ "$a" -lt 10 ]    # this is loop1
do
   b="$a"
   while [ "$b" -ge 0 ]  # this is loop2
   do
      echo -n "$b "
      b=`expr $b - 1`
   done
   echo
   a=`expr $a + 1`
done

for

       for name [ in word ] ; do list ; done
              The list of words following in is expanded, generating a list of items.  The variable name is set to each element of this list in turn,  and list is executed each time.  If the in word is omitted, the for command executes list once for each positional parameter that is set (see PARAMETERS below).  The return status is the exit status of the last command that executes.  If  the  expansion of the items following in results in an empty list, no commands are executed, and the return status is 0.

       for (( expr1 ; expr2 ; expr3 )) ; do list ; done
              First,  the  arithmetic  expression  expr1  is evaluated according to the rules described below under ARITHMETIC EVALUATION.  The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero.  Each time expr2  evaluates  to  a  non-zero value,  list  is  executed  and  the arithmetic expression expr3 is evaluated.  If any expression is omitted, it behaves as if it evaluates to 1.  The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid.
              
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
              The  if list is executed.  If its exit status is zero, the then list is executed.  Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes.  Otherwise, the else  list  is executed, if present.  The exit status is the exit status of the last command executed, or zero if no condition tested true.

       while list; do list; done
       until list; do list; done
              The  while  command  continuously  executes  the do list as long as the last command in list returns an exit status of zero.  The until command is identical to the while command, except that the test is negated; the do list is executed as  long  as  the  last command  in  list returns a non-zero exit status.  The exit status of the while and until commands is the exit status of the last do list command executed, or zero if none was executed.              

break

#!/bin/sh

a=0

while [ $a -lt 10 ]; do
  echo $a
  if [ $a -eq 5 ]; then
    break
  fi
  a=$(expr $a + 1)
done

continue

#!/bin/sh

NUMS="1 2 3 4 5 6 7"

for NUM in $NUMS; do
  Q=$(expr $NUM % 2)
  if [ $Q -eq 0 ]; then
    echo "Number is an even number!!"
    continue
  fi
  echo "Found odd number"
done

函数

   Shell Function Definitions
       A shell function is an object that is called like a simple command and executes a compound command with a new set of positional  parame-
       ters.  Shell functions are declared as follows:

       [ function ] name () compound-command [redirection]
              This  defines  a  function  named  name.  The reserved word function is optional.  If the function reserved word is supplied, the
              parentheses are optional.  The body of the function is the compound command compound-command (see Compound Commands above).  That
              command  is  usually  a  list  of  commands  between  { and }, but may be any command listed under Compound Commands above.  com-
              pound-command is executed whenever name is specified bas the name of a simple command.  Any redirections (see  REDIRECTION  below)
              specified  when  a  function is defined are performed when the function is executed.  The exit status of a function definition is
              zero unless a syntax error occurs or a readonly function with the same name already exists.  When executed, the exit status of  a
              function is the exit status of the last command executed in the body.  (See FUNCTIONS below.)
#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World"
}

# Invoke your function
Hello

Pass Parameters to a Function

#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World $1 $2"
}

# Invoke your function
Hello Zara Ali

Returning Values from Functions

#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World $1 $2"
   return 10
}

# Invoke your function
Hello Zara Ali

# Capture value returnd by last command
ret=$?

echo "Return value is $ret"

运算符

关系运算符(Equality Operators)

Integer

关系运算符只支持数字,不支持字符串,除非字符串的值是数字。

下表列出了常用的关系运算符,假定变量 a 为 10,变量 b 为 20:

运算符 说明 举例
-eq 检测两个数是否相等,相等返回 true。 [ $a -eq $b ] 返回 false。
-ne 检测两个数是否不相等,不相等返回 true。 [ $a -ne $b ] 返回 true。
-gt 检测左边的数是否大于右边的,如果是,则返回 true。 [ $a -gt $b ] 返回 false。
-lt 检测左边的数是否小于右边的,如果是,则返回 true。 [ $a -lt $b ] 返回 true。
-ge 检测左边的数是否大于等于右边的,如果是,则返回 true。 [ $a -ge $b ] 返回 false。
-le 检测左边的数是否小于等于右边的,如果是,则返回 true。 [ $a -le $b ] 返回 true。

Demo

In Bash, you should do your check in an arithmetic context:

if (( a > b )); then
    ...
fi

For POSIX shells that don’t support (()), you can use -lt and -gt.

$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0

One line:

echo $(( a < b ? a : b ))

String

$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1
$ [[ "abc" != "ABC" ]]; echo $?
0

Command Substitution

​ Command substitution allows the output of a command to replace the command name. There are two forms:

          $(command)
   or
          `command`

   Bash  performs  the  expansion by executing command and replacing the command substitution with the standard output of the command, with
   any trailing newlines deleted.  Embedded newlines are not deleted, but they may be removed during word splitting.  The command substitu-
   tion $(cat file) can be replaced by the equivalent but faster $(< file).

   When  the  old-style  backquote  form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \.
   The first backquote not preceded by a backslash terminates the command substitution.  When using the  $(command)  form,  all  characters
   between the parentheses make up the command; none are treated specially.

   Command substitutions may be nested.  To nest when using the backquoted form, escape the inner backquotes with backslashes.

   If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.

Example

Command substitution is generally used to assign the output of a command to a variable. Each of the following examples demonstrates the command substitution −

#!/bin/sh

DATE=`date`
echo "Date is $DATE"

USERS=`who | wc -l`
echo "Logged in user are $USERS"

UP=`date ; uptime`
echo "Uptime is $UP"

Upon execution, you will receive the following result −

Date is Thu Jul  2 03:59:57 MST 2009
Logged in user are 1
Uptime is Thu Jul  2 03:59:57 MST 2009
03:59:57 up 20 days, 14:03,  1 user,  load avg: 0.13, 0.07, 0.15

Variable Substitution

Variable substitution enables the shell programmer to manipulate the value of a variable based on its state.

Here is the following table for all the possible substitutions −

Sr.No. Form & Description
1 **${var}**Substitute the value of var.
2 **${var:-word}**If var is null or unset, word is substituted for var. The value of var does not change.
3 **${var:=word}**If var is null or unset, var is set to the value of word.
4 **${var:?message}**If var is null or unset, message is printed to standard error. This checks that variables are set correctly.
5 **${var:+word}**If var is set, word is substituted for var. The value of var does not change.

Example

Following is the example to show various states of the above substitution −

#!/bin/sh

echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"

echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"

unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"

var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"

echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"

bUpon execution, you will receive the following result −

Variable is not set
1 - Value of var is
Variable is not set
2 - Value of var is Variable is not set

3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix

Reference