shell脚本(其一)


来自于《计算机教育中缺失的一课》02

案例脚本一

创建一个目录,并切换到创建的目录

# mcd.sh
mcd(){
    mkdir -p "$1"
    cd "$1"
}

可将mcd.sh 加载到当前对话框source mcd.sh ,之后,当前对话中就可以使用mcd方法了

案例脚本二

过滤指定文件,查询文件内容中是否包含“foobar”,

输出脚本运行的日期、脚本名、参数数量、进程号,

如果不包含,打印文件名,并将“# foobar”追加到文件尾

#!/bin/bash

echo "Starting program at $(date)" # Date will be substituted

echo "Running program $0 with $# arguments with pid $$"

for file in "$@"; do
    grep foobar "$file" > /dev/null 2> /dev/null
    # When patten is not found, grep has exist status
    # We redirect STDOUT and STDERR to a null register ...e about thme
    if [[ "$?" -ne 0 ]]; then
        echo "File $file does not have any foobar, adding one"
        echo "# foobar" >> "$file"
    fi
done

执行结果

[root@support-192-168-200-163 test]# ls
example.sh  test1.txt  test2.txt  test3.txt  test4.txt  test5.txt
[root@support-192-168-200-163 test]# sh example.sh test*
Starting program at 2023年 05月 16日 星期二 17:49:22 CST
Running program example.sh with 5 arguments with pid 28754
File test2.txt does not have any foobar, adding one
File test4.txt does not have any foobar, adding one
[root@support-192-168-200-163 test]# cat test2.txt 
fobarcsacdaseceascaca
# foobar

说明:

  • $(date) 取当前时间
  • $0 当前脚本文件名
  • $# 参数数量,如果有星号,优先计算星号
  • $$ 进程号
  • $@ 所有参数
  • 2> /dev/null 表示将错误信息重定向到null,也就是忽略掉错误提示信息的意思
  • $? 上一次执行脚本的结果码,0表示真,1表示假
  • -ne 不等于

附注:

-eq 等于,equals

-ne 不等于,no equals

-gt 大于,greater than

-lt 小于,less than

-ge 大于等于,greater equals

-le 小于等于,less equals

案例脚本三

列举匹配的文件

ls test*

列举匹配的文件夹下的文件

ls dir?

参数匹配

ll test{1,2,3}.txt
# test1.txt test2.txt test3.txt
ll test{,1,2,3}.txt
# test.txt test1.txt test2.txt test3.txt
touch project{1,2}/src/test/test{1,2,3}.py
ll test{1..3}.txt
# test1.txt test2.txt test3.txt
# 比较两个文件夹的不同
diff <(ls foo) <(ls bar)

文章作者: 噢买了买了嘎
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 噢买了买了嘎 !
  目录