Linux shell 编程

2020-04-09  本文已影响0人  wayyyy

shell脚本

$PATH环境变量

为什么我们可以在任何路径执行ls命令了?
是因为环境变量$PATH的帮助,当我们执行一个命令,系统会按照PATH的设置去每个PATH定义的目录下查询文件名为ls的可执行文件,如果多个目录有同名的文件,那么先查询到的先执行。

$ echo $PATH
  /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
type命令
"" 和 ''区别
重定向
eval
数据流重定向
命令执行判断
shell变量

疑问:shell环境变量以及set,env,export的区别?

shell 脚本执行方式
shell 脚本默认变量
变量 意义
$# 指传给脚本的参数个数
$0 指脚本文件本身名字
$@ 传给脚本的所有参数(不包括$0)
$$ 是脚本运行的当前进程ID号
$? 显示最后一个命令的退出状态,0表示没有错误,其他表示有错误
语法
数值运算
#! /bin/bash

service_port=10000
log_service_port=$(expr $(service_port) + 1)
shell 函数返回字符串

shell函数只能返回数字,不允许返回字符串,但是可以用点小技巧返回字符串。

#! /bin/bash

function return_str()
{
    local l_str="hello world"
    echo "${l_str}"
}

str=$(return_str)
echo ${str}
向函数传递数组和从函数返回数组
local
var="hello"

function test()
{
    local var="world";
    echo "${var}"
}

test    // 输出 world
数组

shell中的数据分为2类:一类是普通数组,另一类是关联数组。

字符串替换

https://www.cnblogs.com/gaochsh/p/6901809.html

判断一个变量是否为空
#!/bin/bash

function check_var_is_null()
{
    local l_var=$1
    if [ ! -n "${l_var}" ]; then
        echo "var is null"
    else
        echo "var is not null"
    fi
}

para1=""
para2=
check_var_is_null ${para1}
check_var_is_null ${para2}
对文件和目录存不存在
#!/bin/bash

function file_is_exist()
{
    local l_file=$1
    if [ -f "${l_file}" ]; then
        echo "found"
    else
        echo "not found"
    fi
}
判断式 意义
-e filename 判断文件名是否存在
-f filename 判断文件名是否存在且为文件
-d filename 判断文件名是否存在且为目录
-b -c -S -p -L 判断文件名是否存在且为块设备,字符设备,Socket文件,管道文件,连接文件
-r filename 检测该文件名是否存在且具有读权限
-w filename 检测该文件名是否存在且具有写权限
-x filename 检测该文件名是否存在且具有执行权限
n1 -eq/ne/gt/ge/lt/le n2 n1 相等/不等/大于/大于等于/小于/小于等于 n2
str1 = str2 字符串str1是否等于字符串str2
str1 != str2 字符串str1是否不等于str2
-z str 判断字符串str是否为空串
-a 2个条件同时成立 -r file -a test -x file
-o 任何一个条件成立
反向
文本替换
#!/bin/bash

function global_replace() {
    local l_file=$1
    local l_old_word=$2
    local l_new_word=$3

    eval sed -i 's/${l_old_word}/${l_new_word}/g' ${l_file}
    if [ $? -ne 0 ]; then
        echo "error: replace word faild, exit"
        exit 1
    fi
}
函数传参注意
#!/bin/bash
function func_param()
{
    local l_var=$1;
    echo "${l_var}"
}

mysql_user_info="-usheng -psheng0"
func_param ${mysql_user_info}        // 输出 -usheng
func_param "${mysql_user_info}"      // 输出 -usheng -psheng0
推荐一个shell代码片段学习

https://github.com/dylanaraps/pure-bash-bible

编写可靠shell脚本技巧
shellcheck

shellcheck 是一款实用的 shell脚本静态检查工具。
项目地址:https://github.com/koalaman/shellcheck
ubuntu 安装

apt-get install shellcheck
多任务并行
#!/bin/bash

for i in {1..254};do
    ip="192.168.80.$i"
    ping -c 2 $ip &> /dev/null && echo $ip is up &
done

wait

参考资料

  1. https://zhuanlan.zhihu.com/p/123989641
上一篇 下一篇

猜你喜欢

热点阅读