shell的一些语法及例子

shell调试太难了,语法也难懂,扒了一些例子,方便查找

1. 输出help信息

function print_help() {
    cat <<EOF
  --debload                     
  --dpdkpath                   
  -k, --dpdk                  
EOF
}

2. case语句

    case "$1" in
        "") echo "${USER}_$(date +'%Y%m%d-%H%M')";;
        *)  echo "$1";;
    esac

3. 接收shell输出结果,输出到文件

    commit=$( (cd "${REPO_DIR}"; git rev-parse HEAD))
    {
        echo "NAME=\"C TEST\""
        echo "PRODUCT=\"${PRODUCT_NO}\""
	    echo "VERSION=\"${RSTATE}\""
        echo "COMMIT=\"${commit}\""
    } > "${RELEASE_FILE}"

4. 判断相等大小

# 判断两个变量是否相等
if [ "$var1" = "$var2" ]; then
    echo "var1 and var2 are equal"
fi

# 判断两个变量是否不相等
if [ "$var1" != "$var2" ]; then
    echo "var1 and var2 are not equal"
fi

# 判断 var1 是否大于 var2
if [ "$var1" -gt "$var2" ]; then
    echo "var1 is greater than var2"
fi

# 判断 var1 是否小于 var2
if [ "$var1" -lt "$var2" ]; then
    echo "var1 is less than var2"
fi

# 判断 var1 是否大于等于 var2
if [ "$var1" -ge "$var2" ]; then
    echo "var1 is greater than or equal to var2"
fi

# 判断 var1 是否小于等于 var2
if [ "$var1" -le "$var2" ]; then
    echo "var1 is less than or equal to var2"
fi

if [ $PF -eq 1 ]; then
      PF_CMD="--prof"
fi

if [ "$RUN" -ne 0 ]; then
    return
fi

5. mkdir -p 连接字符串

mkdir -p "${REPO_TOP}"/scripts

6. 是否是文件,是否是文件夹

# 检查是否是文件
if [ -f "$path" ]; then
    echo "$path is a file"
else
    echo "$path is not a file"
fi

# 检查是否是目录
if [ -d "$path" ]; then
    echo "$path is a directory"
else
    echo "$path is not a directory"
fi

7. for循环

AGENTS=('seli' 'seli2' 'seli0' 'se3' 'se5')
    for host in "${AGENTS[@]}"
    do
        if [ "${host}.com" == "$HOSTNAME" ]; then
            export D_H=tcp://gi:2673
        fi
    done

8. while 循环

while true ; do
    case "$1" in
        -d|--debload) DEBUG_LOAD=1; echo "DEBUG LOAD"; shift;;
        -e|--codechecker) run_codechecker; exit 0;;
        -h|--help) print_help; exit 0;;
        --) shift;;
        "") break;;
        *) error_exit "Unrecognized argument: $1, try $CMD_NAME -h or --help for help." ;;
    esac
done

在 Shell 脚本中,`case` 语句用于根据某个值的不同情况执行不同的命令。它类似于其他编程语言中的 `switch` 语句。

在你给出的脚本中:

​```shellscript
while true ; do
    case "$1" in
        -d|--debload) DEBUG_LOAD=1; echo "DEBUG LOADDDDDDDD"; shift;;
        -e|--codechecker) run_codechecker; exit 0;;
        -h|--help) print_help; exit 0;;
        -p|--prof) PROFILING=1; echo "PROFFFFFF"; shift;;
        -m|--mct) MCT_MODE=1; echo "Compiling for MCT"; shift;;
        --) shift;;
        "") break;;
        *) error_exit "Unrecognized argument: $1, try $CMD_NAME -h or --help for help." ;;
    esac
done```
这段代码在一个无限循环中使用 `case` 语句检查 `$1`(第一个命令行参数)的值。根据 `$1` 的值,脚本会执行不同的命令:
- 如果 `$1``-d``--debload`,脚本会设置 `DEBUG_LOAD`1,打印一条消息,然后使用 `shift` 命令移除第一个命令行参数。

9. grep awk

LOCAL_UID=$(grep "$USER" /etc/passwd | awk -F ":" '{print $3}')

grep "$USER" /etc/passwd: This command searches for the current user's username in the /etc/passwd file. This file contains one line for each user account, with seven fields delimited by colons (:). The first field is the username, and the third field is the user ID.

awk -F ":" '{print $3}': This command processes the output of the grep command. It uses : as the field delimiter (-F ":"), and prints the third field ('{print $3}'), which is the user ID.

LOCAL_UID=$(...): This sets the variable LOCAL_UID to the result of the command inside the $(...).
grep 是一个强大的文本搜索工具,它使用正则表达式来搜索文本,并打印出匹配的行。以下是 grep 的一些常用参数:
-i: 忽略大小写。在搜索时,grep 会忽略大小写。
-v: 反向选择。只打印不匹配的行。
-r 或 -R: 递归。在给定目录及其子目录下搜索。
-l: 只打印文件名。当文件中有匹配的行时,只打印文件名。
-L: 只打印不包含匹配的文件名。
-c: 只打印匹配的行数。不显示匹配的内容。
-n: 显示行号。在显示匹配的行时,同时显示行号。
-e pattern 或 --regexp=pattern: 使用模式进行搜索。你可以使用这个选项多次来搜索多个模式。
-f file--file=file: 从文件中读取模式。
-w 或 --word-regexp: 只匹配整个单词,而不是字符串的一部分。
-x 或 --line-regexp: 只匹配整行。
-q"quiet" 的缩写。当使用 -q 选项时,grep 不会打印任何输出。它只是简单地返回一个状态码,如果找到了匹配的文本,状态码为 0,否则为非零。

10. wget命令

cd "$FOLDER" || exit 1; timeout --preserve-status 40s wget -S \
https://arm.sero.gic.ericsson.se/artifactory/proj-codechecker-release-generic-local/"$CODECHECKER_RELEASE" \
-o /dev/stdout 2>&1 | grep -E 'HTTP/.* 200' > /dev/null 2>&1
RES=$?

- `cd "$FOLDER" || exit 1;`: This line changes the current directory to the directory specified by the `FOLDER` variable. If the `cd` command fails (for example, if the directory doesn't exist), the script will exit with a status of 1.

- `timeout --preserve-status 40s wget -S ...`: This line runs the `wget` command to download a file from a URL. The `timeout --preserve-status 40s` part means that if the `wget` command takes more than 40 seconds to complete, it will be stopped and the script will continue to the next command. The `-S` option tells `wget` to print the server response.

- `https://arm.sero.gic.ericsson.se/artifactory/proj-codechecker-release-generic-local/"$CODECHECKER_RELEASE"`: This is the URL that `wget` is downloading from. The `CODECHECKER_RELEASE` variable is appended to the end of the URL, so it's likely the name or version of the CodeChecker release that the script is trying to download.

- `-o /dev/stdout 2>&1 | grep -E 'HTTP/.* 200' > /dev/null 2>&1`: This part redirects the output of the `wget` command to `stdout` and then pipes it to the `grep` command. The `grep` command is looking for a line that matches the regular expression 'HTTP/.* 200', which would indicate a successful HTTP request. The output of the `grep` command is then redirected to `/dev/null`, effectively discarding it.

- `RES=$?`: This line sets the variable `RES` to the exit status of the last command. If the `wget` command was successful, `RES` will be 0. If the `wget` command failed or was stopped by the `timeout` command, `RES` will be a non-zero value.

11. sed以及替换命令

sed -i "/#CODECHECKER_INSTALL/a\\
  ${ICMDS}" "$DOCKER_FILE"

所以,这个 `sed` 命令的作用是在 Dockerfile 中找到 `#CODECHECKER_INSTALL`,然后在它后面添加 `INSTALL_COMMANDS` 中的命令。

ICMDS="${INSTALL_COMMANDS//$'\n'/\\$'\n'}"

- `${INSTALL_COMMANDS//$'\n'/\\$'\n'}`:这是 Shell 脚本中的参数扩展。它将 `INSTALL_COMMANDS` 变量中的所有换行符(`$'\n'`)替换为反斜杠后跟换行符(`\\$'\n'`)。

CONTAINER_ID=$(sed -n 1p docker_start_log.txt)
在这行 shell 脚本中,`sed -n 1p docker_start_log.txt` 是正在执行的 `sed` 命令。`sed` 是一个用于过滤和转换文本的流编辑器。`-n` 选项抑制了自动打印,`1p` 命令告诉 `sed` 打印文件的第一行。所以,这个命令从 `docker_start_log.txt` 读取第一行。

12. getopt

 getopt -o edh --long debload,help,dpdkpath -n "build.sh" -- "--debload"
 --debload --
- `getopt -o ${ltr_opts} --long ${wrd_opts} -n "${CMD_NAME}" -- "$@"`:这是正在执行的 `getopt` 命令。`getopt` 是一个解析命令行选项和参数的程序。
- `-o ${ltr_opts}``-o` 选项后跟 `${ltr_opts}` 指定了短选项。短选项是单个字符,前面带有一个短划线。`${ltr_opts}` 变量可能包含一串短选项字符。
- `--long ${wrd_opts}``--long` 选项后跟 `${wrd_opts}` 指定了长选项。长选项是单词,前面带有两个短划线。`${wrd_opts}` 变量可能包含一串用逗号分隔的长选项单词。
- `-n "${CMD_NAME}"``-n` 选项后跟 `${CMD_NAME}` 指定了将在错误消息中使用的脚本名称。
- `-- "$@"``--` 表示选项的结束。`"$@"` 是一个特殊变量,包含传递给脚本的所有命令行参数。
- `temp=$(...)`:这是一个命令替换。它运行括号内的命令(`...`)并将其输出分配给 `temp` 变量。在这种情况下,它将解析的命令行选项和参数存储在 `temp` 中。
这行代码的效果是解析传递给脚本的命令行选项和参数,并将它们存储在 `temp` 中。这对于以灵活的方式处理不同的选项和参数可能很有用。
 

13. 查找文件中的字符串

find . -type f -name "*meson*" -exec grep -l "make" {} \;

find . -type f -name "*meson*": 在当前目录(.)及其子目录中查找所有名字包含 "meson" 的文件。-type f 表示只查找文件,不包括目录。

-exec grep -l "make" {} \;: 对每个找到的文件执行 grep -l "make" 命令。grep -l "make" 命令会在文件中查找 "make" 字符串,如果找到,就打印文件名。{}find 命令找到的文件名,\; 表示 -exec 选项的结束。

14. 模糊查找文件名,并查找文件内容

#!/bin/bash

meson_files=$(find . -type f -name "meson.build")

for file in $meson_files
do
    grep -q $1 $file
    if [ $? -eq 0 ]; then
        echo "find $1 in $file"
    fi
done

15. 路径查找并返回

#Move to folder where script is located, to extract path, then move back
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
pushd "$SCRIPT_DIR" 1>/dev/null || exit
REPO_ROOT="$(realpath ../../)"
popd 1>/dev/null || exit

16. mapfile

# Get list of modified files one commit ahead of master, exclude deleted files
MODIFIED_FILES_STRING=$(git diff --name-only --diff-filter=d HEAD~1)
# Convert newline separated strings to array
mapfile -t MODIFIED_FILES <<< "$MODIFIED_FILES_STRING"

mapfile -t MODIFIED_FILES: The mapfile command, also known as readarray, reads lines from the standard input into an array variable. The -t option tells mapfile to strip a trailing newline from each line read. MODIFIED_FILES is the name of the array variable.

<<< "$MODIFIED_FILES_STRING": This is a here string in bash. It redirects a string into the standard input of a command. "$MODIFIED_FILES_STRING" is a variable that holds the string to be redirected.

17. 查找目录中文件,并复制到其它目录

  1 #!/bin/bash
  2
  3
  4 # search from . find $1 file and copy to path $2
  5
  6 files_=$(find . -type f -name "*$1*")
  7
  8 for file in $files_
  9 do
 10         new_name=$(echo $file | sed 's/\//_/g')
 11         new_name=$(echo $new_name | sed 's/\.//g')
 12         echo $new_name
 13         cp -r $file $2"/"$new_name
 14 done

18 查看文件夹大小

du -h --max-depth=1 .

19 安装deb文件

sudo dpkg -i ninja-build_1.8.2-1_arm64.deb
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值