Linux Shell Program Tutorial(3)

20. Functions

#!/bin/bash

function print () {
echo $1 $2 $3
}

quit () {
    exit
}

print Hello World Again

echo "foo"
quit

21. Local variables

#!/bin/bash

function print () {
    local name=$1
 # keyword local whether there is 'local' is different
    echo "The name is $name"
}

name="Tom"
echo "The name is $name : Before"

print Max
echo "The name is $name : After"
 # If there is no 'local' above , the variable 'name' is Max; Otherwise, it will be Tom.

echo "foo"

22. Function example

#!/bin/bash

usage(){
    echo "You need to provide an argument : "
    echo "usage : $0 file_name"
}

is_file_exist(){
    local file="$1"
    [[ -f "$file" ]] && return 0 || return 1
}

[[ $# -eq 0 ]] && usage

if ( is_file_exist "$1" )
then
    echo "File found"
else
    echo "File not found"
fi

23. Readonly command

#!/bin/bash

var=31

readonly var

var=50

echo "var => $var"

hello(){
    echo "Hello World"
}

readonly -f hello


hello(){
    echo "Hello World Again"
}

readonly -f #all functions are read only
readonly -p  #all variables are read only

24. Signals and traps

#!/bin/bash

echo "pid is $$"
while ((COUNT < 10))
do
    sleep 10
    ((COUNT ++))
    echo $COUNT
done
exit 0

>> kill -9 jobname

#!/bin/bash

#trap "echo Exit signal is detected" SIGINT
#trap "echo Exit signal is detected" SIGKILL

file=/home/maq/work-miao/shelllearning/file1.txt
trap "rm -f $file && echo file deleted; exit" 0 2 15

echo "pid is $$"
while ((COUNT < 10))
do
    sleep 10
    ((COUNT ++))
    echo $COUNT
done
exit 0

25. How to debug a bash script

  • #!/bin/bash -x

  • >> bash -x hello.h

  • set -x #start to debug

  • set +x #end debugging

#!/bin/bash -x
#trap "echo Exit signal is detected" SIGINT
#trap "echo Exit signal is detected" SIGKILL

#set -x
file=/home/maq/work-miao/shelllearning/file1.txt
#set +x
trap "rm -f $file && echo file deleted; exit" 0 2 15

echo "pid is $$"
while ((COUNT < 10))
do
    sleep 10
    ((COUNT ++))
    echo $COUNT
done
exit 0

以上内容参考bilibili站视频https://www.bilibili.com/video/av51517726

 

/*今日标签*/

不介意孤独

比爱你更舒服

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值