Bash shell:bash脚本示例

示例1:函数与local局部变量的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/bash
foo1=hello
foo2=world
echo "$foo1" #双引号里的变量转义, 输出hello
echo '$foo1' #单引号里的变量不会被转义, 直接输出$foo1
 
mcd(){
    echo -n "$0 " #-n 不换行
    echo -n "$1 "
    echo "$2" #$0脚本名, $1第一个参数, 以此类推
    mkdir "$1"
    cd "$1"
    touch "$2"
}
 
func(){
    echo `date "+%F %T"`': func() start'
    local foo1='localhello' #()内的变量是局部变量, {}内的变量影响整个shell, 采用local改变{}内的变量只在局部有效
    foo2='localworld'
    echo -n "$foo1 "
    echo $foo2
    echo `date "+%F %T"`': func() completed successfully'
}
 
 
mcd 'hello' world
 
echo -n "$foo1 "
echo $foo2
func #如果采用func()()的形式, 31-32行输出hello world
echo -n "$foo1 "
echo $foo2

  执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
karinto@server:~$ ./foo
hello
$foo1
./foo hello world
hello world
2023-03-11 01:27:58: func() start
localhello localworld
2023-03-11 01:27:58: func() completed successfully
hello localworld #31-32行输出
karinto@server:~$ tree
.
├── foo
└── hello
    └── world
 
1 directory, 2 files

 

示例2:for循环、if判断的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash
 
foo(){
    echo `date "+%F %T"`': foo() start'
    echo "Running program $0 with $# argument(s) with pid $$" # $#表示参数个数, $$表示process id
    for file in $(ls $1); do
        grep --ignore-case 'con' "$1/$file" > /dev/null 2> /dev/null #打印信息输出到黑洞
        if [[ $? -ne 0 ]]; then #前一个命令的返回值!=0, false
            echo "File $1/$file does not have any con"
        else
            echo "Con have found in file $1/$file"
        fi
    done
}
 
dif(){
    echo '------------dif()------------'
    diff -W 80 -y $1 $2 #-y并列显示 -W拉开一定距离
    echo '-------------end-------------'
}
 
foo '/wrk'
dif /wrk/curl_{1,2} #正则, 等同于dif '/wrk/curl_1' '/wrk/curl_2'

  执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
karinto@server:/wrk$ ~/command_substitution
2023-03-11 09:14:34: foo() start
Running program /home/karinto/command_substitution with 1 argument(s) with pid 2335
Con have found in file /wrk/curl_1
Con have found in file /wrk/curl_2
File /wrk/ping does not have any con
------------dif()------------
HTTP/1.1 200 OK                       | HTTP/1.1 403 Forbidden
Accept-Ranges: bytes                  | Server: nginx
Cache-Control: private, no-cache      | Date: Sat, 11 Mar 2023 08:34:39 GMT
Connection: keep-alive                <
Content-Length: 277                   <
Content-Type: text/html                 Content-Type: text/html
Date: Sat, 11 Mar 2023 08:31:49       | Content-Length: 162
Etag: "575e1f59-115"                  | Connection: keep-alive
Last-Modified: Mon, 13 Jun 2016       <
Pragma: no-cache                      <
Server: bfe/1.0.8.18                  <
 
-------------end-------------

 

posted @   karinto  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示