巩鹏军的博客

HOME

常用Shell脚本模版

26 Feb 2023

经常写shell脚本时忘了某个具体语法怎么写,写个模版备忘。

1、参数判断

模版:

#!/bin/bash

script_name=`basename "$0"`
if [ $# -gt 1 ]; then
    echo "USAGE: ./${script_name} {file_name} OR cat | ./${script_name}"
    echo "e.g.: ./${script_name} sample.txt"
    echo "e.g.: cat sample.txt | ./${script_name}"
    exit;
fi

说明:

2、遍历文件

模版:

#!/bin/bash
filename="${1:-/dev/stdin}"
n=1
while read -r line;
do
  echo "line $n : ${line}"
  n=$((n+1))
done < ${filename}

说明:

输出:

$ cat os.txt
CentOS 7.2
Ubuntu
Debian
LinuxMint
$ ./read_line_by_line.sh os.txt
line 1 : CentOS 7.2
line 2 : Ubuntu
line 3 : Debian
line 4 : LinuxMint
$ cat os.txt | ./read_line_by_line.sh
line 1 : CentOS 7.2
line 2 : Ubuntu
line 3 : Debian
line 4 : LinuxMint

参考:https://linuxhint.com/while_read_line_bash/

3、遍历数组

模版:

#!/bin/bash

declare -a array=("element 1"
                  "element 2" "element 3"
                  "element 4")

echo "iterate element only in array:"
for element in "${array[@]}"
do
   echo "${element}"
done

echo "iterate element and index in array:"
length=${#array[@]}
for (( i=0; i<${length}; i++ ));
do
  echo "array[$i]: ${array[$i]}"
done

输出:

iterate element only in array:
element 1
element 2
element 3
element 4
iterate element and index in array:
array[0]: element 1
array[1]: element 2
array[2]: element 3
array[3]: element 4

4、显示命令

#!/bin/bash

CMD="df -kh"
echo $CMD
exec $CMD

参考:

关于我

专注于IM即时通讯全技术栈的程序员,关注获取更多IM技术文章。

gongpengjunblog

IM小蓝天

微信扫描二维码,关注我的公众号