artificerpi

Shell(BASH) 编程

SHELL PROGRAMMING

 

目录:

1.shell简单介绍

2.shell 编程准备知识

3.shell编程结构化语言构建

4.其他

5.shell编程的两个示例

写在前面:

1.Hello World示例

</> hello.sh

#!/bin/bash
# This is an example of bash HelloWorld
# You can start shell programming with an Hello World example
echo 'Hello World'

保存该内容到hello.sh,然后在终端运行它 `./hello.sh` , 就会看到 `Hello World` 消息。

 

2.计算1+1=2

</> expr.sh

#!/bin/bash
#
# This example will bring you to bash shell more deeply.
# Function: add two input numbers and then print the result.

if [ $# -ne 2 ]                                # error handling
then
    echo "Usage - $0   x    y"                 # display help message 
    echo "        Where x and y are two nos for which I will print sum"
    exit 1
fi
    echo "Sum of $1 and $2 is `expr $1 + $2`"

 原理:  expr(evaluate expressions)命令: 例如 `expr 1 + 2` 将会输出 3

要了解更多关于expr命令的知识,输入 `man expr`

 

正文:

 

1.shell简单介绍

  我们都知道,计算机识别的是二进制语言,计算机指令也是用二进制来表示的,但这对我们来说却相当困难。所以在一些操作系统中就有一个特殊程序叫做shell, shell接受你输入的指令,并且如果它是正确的话,就会将该指令传递到内核。

  shell是一个用户程序或者说是一种由计算机与用户交互的环境。shell是一种解释型语言,可以执行来自标准输入设备(键盘)或者是文件的命令。 Linux shell跟windows command 类似,但是前者功能更为强大。

  shell有许多种,本文中主要介绍的是bash (Bourne Again shell), 一种比较流行的shell语言,很多unix系统中都会默认集成它。

 

 

2.shell 编程准备知识

 2.1 shell 变量

  2.1.1 设置环境变量

    如果变量已存在,直接赋值就行 (注意,不同于windows, unix-like系统中,变量和路径大小写敏感 case-sensitivity)

LANG=he_IL.UTF-8

    如果不存在,加上 `export`语句即可 (先设置了shell变量,再 export为了环境变量)

EDITOR=nano
export EDITOR

  2.1.2 检测环境变量

printenv                                    # 打印当前所有的环境变量
printenv TERM                               # 打印`TERM`环境变量
echo $TERM                                  # 输出`TERM`环境变量的值

  2.1.3 清除环境变量

export TERM=                                  # 设置为空
export -n TERM                                #    un-export
unset TERM                                    # 删除变量 TERM

  2.1.4 配置文件

  • 系统变量

  主要的配置文件:

    `/etc/environment`  非脚本,主要包含一些环境变量赋值表达式

    `/etc/profile.d/*.sh` (注意 `/etc/profile` 作为基础的配置文件,所以一般不直接编辑它)

  • 用户变量

    ` ~/.pam_environment `  (一般由GUI等程序修改,不要手动编辑)

    `~/.profile`    (run after `~/.pam_environment` has been read,可以覆盖 `.pam_environment`文件里的配置) 一般登录后生效

    其他 bash: Shell config files such as ~/.bashrc~/.bash_profile, and ~/.bash_login are often suggested for setting environment variables. While this may work on Bash shells for programs started from the shell, variables set in those files are not available by default to programs started from the graphical environment in a desktop session. 

    一般如无特殊需要,修改`~/.bashrc`就行了。

  2.1.5 shell参数

  • $符号,取出变量值
$$   Shell本身的PID(ProcessID)
$!    Shell最后运行的后台Process的PID
$?        最后运行的命令的结束代码(返回值)
$-         使用Set命令设定的Flag一览
$*         所有参数列表。如"$*"用「"」括起来的情况、以"$1 $2 … $n"的形式输出所有参数。
$@       所有参数列表。如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数。
$#        添加到Shell的参数个数
$0        Shell本身的文件名
$1~$n    参数值

  

 

 2.2 输入输出 (I/O)

 input: read

 output: echo

 

2.3 shell 算术

a=$((1 + 2 * 3));

b=$(expr 3 + 2);

echo $a

echo $b

 

2.4 引号与注释

  • 单行注释  a shebang or "bang" line

  使用#符号注释一行

#!/bin/bash
# This is a comment of the helloworld, (shebang)
echo "Hello World!"
  • 多行注释 Mulitple line comment

   1). 使用Here Document   (<<COMMENT1 到 COMMENT1结束部分被注释) 

#!/bin/bash
echo "Say Something"
<<COMMENT1
    This is a Hello World
    comment 2
    blah
COMMENT1
echo "Hello World"

  2). 使用 : shell builtin command  (or do-nothing command)

#!/bin/bash
: '
 your comments here
'
echo "Hello World"

  man page of : builtin command

: [arguments]
No effect; the command does nothing beyond expanding arguments
and performing any specified redirections. A zero exit code is
returned.
View Code

 

 

  

2.5 管道Pipes

 

2.5 Filters

 

2.7 其他

 

3.shell编程结构化语言构建

 3.1 if条件语句

       语法:

if condition
    then
        command1 if condition is true or if exit status
        of condition is 0 (zero)
        ...
        ...
    fi

例子:

The cat command return zero(0) i.e. exit status, on successful, this can be used, in if condition as follows, Write shell script as

 

$ cat > showfile
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
fi

 

if-than-else-fi语法:

 if condition
           then
                       condition is zero (true - 0)
                       execute all commands up to else statement

           else
                       if condition is not true then
                       execute all commands up to fi
           fi

 

    嵌套if语句:

if condition
    then
        if condition
        then
            .....
            ..
            do this
        else
            ....
            ..
            do this
        fi
    else
    if condition
       then
            .....
            ..
            do this
        else
            ....
            ..
            do this
fi
fi

 

 

test 命令 或 [真值语句]

         test命令和[expr]都可以用来判断一条语句是否为真,如果该语句为真则返回0,否则返回非0值为假。

用法:

test expression OR [ expression ]

例子,判断一个数是否为正数:

$ cat > ispostive
#!/bin/sh
#
# Script to see whether argument is positive
#
if test $1 -gt 0
then
echo "$1 number is positive"
fi

更多资料:(英文,更接近与代码,所以不翻译了)

test or [ expr ] works with
1.Integer ( Number without decimal point)
2.File types
3.Character string

For Mathematics, use following operator in Shell Script

Mathematical Operator in  Shell Script  Meaning Normal Arithmetical/ Mathematical Statements But in Shell
      For test statement with if command For [ expr ] statement with if command
-eq is equal to 5 == 6 if test 5 -eq 6 if [ 5 -eq 6 ]
-ne is not equal to 5 != 6 if test 5 -ne 6 if [ 5 -ne 6 ]
-lt is less than 5 < 6 if test 5 -lt 6 if [ 5 -lt 6 ]
-le is less than or equal to 5 <= 6 if test 5 -le 6 if [ 5 -le 6 ]
-gt is greater than 5 > 6 if test 5 -gt 6 if [ 5 -gt 6 ]
-ge is greater than or equal to 5 >= 6 if test 5 -ge 6 if [ 5 -ge 6 ]

NOTE: == is equal, != is not equal.

 

For string Comparisons use

Operator Meaning
string1 = string2 string1 is equal to string2
string1 != string2 string1 is NOT equal to string2
string1 string1 is NOT NULL or not defined 
-n string1 string1 is NOT NULL and does exist
-z string1 string1 is NULL and does exist

Shell also test for file and directory types

Test Meaning
-s file    Non empty file
-f file    Is File exist or normal file and not a directory 
-d dir     Is Directory exist and not a file
-w file   Is writeable file
-r file    Is read-only file
-x file    Is file is executable

Logical Operators

Logical operators are used to combine two or more condition at a time

Operator            Meaning
! expression Logical NOT
expression1  -a  expression2 Logical AND
expression1  -o  expression2 Logical OR

 

 3.2 循环语句 Loop

for循环:
语法1:
for { variable name } in { list }
            do
                     execute one for each item in the list until the list is
                     not finished (And repeat all statement between do and done)
            done
示例:
$ cat > testfor
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done

语法2:
for (( expr1; expr2; expr3 ))
         do
               .....
               ...
               repeat all statements between do and 
               done until expr2 is TRUE
         Done

示例:

$ cat > for2
for ((  i = 0 ;  i <= 5;  i++  ))
do
  echo "Welcome $i times"
done

 

语法3:

嵌套for循环:

$ vi nestedfor.sh
for (( i = 1; i <= 5; i++ ))      ### Outer for loop ###
do

    for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ###
    do
          echo -n "$i "
    done

  echo "" #### print the new line ###

done

 

for i in (seq 1 5)

do 

  echo $i

done

 

while 循环

语法:

 while [ condition ]
           do
                 command1
                 command2
                 command3
                 ..
                 ....
            done

 

 数组

array=( 1 2 3 4 )

for i in array; do

  echo $i

done

str_array=(

  "Hi"

  “Nice to meet you!"

  "Good"

)

for ((i=0; i<${#str_array[*]}; i++))

do 

  echo ${str_array[$i]}

done

 

 

 3.3 case 语句

语法:

case  $variable-name  in
                pattern1)   command
                                ...
                                ..
                                command;;
                pattern2)   command
                                ...
                                ..
                                command;;
                patternN)   command
                                ...
                                ..
                                command;;
                *)             command
                                ...
                                ..
                                command;;
           esac

;; 符号相当于c++中的break语句

 

延伸知识:  ;分号

是多个语句之间的分隔符,

例如下面这句: 

if[XXXXXXXXXXXXX];then

它完全等效于下面的两句:

1: if[XXXXXXXXXXXXX]
2: then

 

 

 3.4 函数 Function

 语法:

定义:

  function-name ( ){
                command1
                command2
                .....
                ...
                commandN
                return
  } 

或者
 function function-name() {
command...
echo "parameter1 is $1, parameter2 is $2 ..."
}

使用:

function-name

 例子:

#!/bin/bash
#
# This is an example of using function in shell programming

# Defination of the function
SayHello(){
    echo ‘Hello’
    return                           # must to return 
}


# Using the SayHello Function
SayHello

 

 3.5 如何debug

可以使用 -v 或 -x 选项来debug shell 脚本

语法:

sh   option   { shell-script-name }
# OR
bash   option   { shell-script-name }
-v Print shell input lines as they are read.   #打印出读入的各行
-x After expanding each simple-command, bash displays the expanded value of PS4 system variable, followed by the command and its expanded arguments

 

 

 

4.其他

 4.1 shell 脚本编写风格

Shell Style Guide By Google

 

5.shell编程的两个示例

 5.1 计算一个数的阶乘

#!/bin/bash
#
# Calculate the factorial of an input integer           # 使用说明

n=0                                                     # 定义三个变量
on=0
fact=1 

echo -n "Enter number to find factorial : "             # 提示用户输入
read n                                          

on=$n                                                   # 给变量赋值

while [ $n -ge  1 ]                                     # 循环满足条件,变量大于或等于1
do
  fact=`expr $fact \* $n`
  n=`expr $n - 1`
done                                                    # 终止循环

echo "Factorial for $on is $fact"                       # 打印出结果

 

 5.2

    //TODO

 

 

参考:

  https://help.ubuntu.com/community/EnvironmentVariables 

  https://help.ubuntu.com/community/Beginners/BashScripting

  特殊字符 http://tldp.org/LDP/abs/html/special-chars.html

posted @ 2015-05-10 11:44  artificerpi  阅读(562)  评论(0)    收藏  举报

Copyright ©2017 artificerpi