shell common statement

A common symbol

$0    当前脚本的文件名
$n    传递给脚本的参数n,比如$1表示第一个参数
$#    传递给脚本或函数的参数个数。
$*,$@ 传递给脚本或函数的所有参数
$?    上个命令的退出状态,或函数的返回值。
$$    当前Shell脚本所在的进程ID

Example:

#!/bin/bash

for var in $*
do
   echo "$var"           #for循环打印所有参数
done

Second, the command separator semicolon ";"

  • Role: You can write two or more commands on the same line

Example:

if [ "$filename" == "$1" ]; then     #执行两条命令
echo "File $filename exists.";fi

Third, the double semicolons ";;"

  • Purpose: In the case statement, which is similar to the case C, to assume the role of break

The shell case syntax is as follows:

case "变量" in
  "变量1")
      ...
  ;;          #这里的双分号类似于break

  "变量2")
      ...
  ;; 

  *)          #匹配剩下的变量n
     ...
  ;; 
esac        #case结束语句

Example:

#!/bin/base

variable=xyz

case "$variable" in
abc) echo "\$variable = abc" ;;
xyz) echo "\$variable = xyz" ;; 
esac

print:

$variable = xyz

Fourth, the single quotation marks' and double quotes "

  • Single quote: will prevent explain all the special characters, enclosed in single quotes contents are ordinary strings
  • Double quotes: up quoted strings, some special characters will play their role

Example:

#!/bin/bash

a="this is a"
b="this is b"

echo '${a}'
echo "${b}"

print:

${a}
this is b

Five anti-quotation marks `and $ ()

  • Action: commands are used to implement alternative, can be assigned to a variable by the output of the command to

Example:

echo $(date "+ %Y/%m/%d %H:%M:%S")     #运行date命令
echo `date "+ %Y/%m/%d %H:%M:%S"`      #运行date命令
c=$(echo hello)                        #打印: c=hello

Guess you like

Origin www.cnblogs.com/princepeng/p/11578652.html