MST

星途 面试题库

面试题:Bash脚本实现复杂API交互及错误处理

有一个文件存储服务API,支持上传文件(POST请求,请求体为文件二进制内容,API地址如http://api.storage.com/upload )和下载文件(GET请求,参数为文件名,API地址如http://api.storage.com/download?filename={filename} )。编写一个Bash脚本,实现:1. 检查本地指定目录下所有文件,将它们逐一上传到该文件存储服务;2. 上传完成后,对每个文件进行下载,并与本地原文件进行md5sum校验,确保文件传输无误;3. 若上传或下载过程中出现任何HTTP错误(如404、500等),在日志文件中详细记录错误信息,包括错误码、错误时间、涉及的文件名等。
32.4万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 本地目录
local_dir="/path/to/local/directory"
# 日志文件路径
log_file="upload_download.log"
# 文件存储服务上传API
upload_api="http://api.storage.com/upload"
# 文件存储服务下载API
download_api="http://api.storage.com/download"

# 函数:记录日志
log_error() {
    local error_code=$1
    local error_time=$(date +%Y-%m-%d\ %H:%M:%S)
    local file_name=$2
    echo "[ERROR] $error_time - HTTP Error $error_code - File: $file_name" >> $log_file
}

# 上传文件
for file in $local_dir/*; do
    if [ -f "$file" ]; then
        file_name=$(basename "$file")
        response=$(curl -s -o /dev/null -w "%{http_code}" -X POST -T "$file" $upload_api)
        if [ "$response" -ne 200 ]; then
            log_error $response $file_name
            continue
        fi
        echo "Uploaded $file_name successfully"
    fi
done

# 下载文件并校验md5sum
for file in $local_dir/*; do
    if [ -f "$file" ]; then
        file_name=$(basename "$file")
        local_md5=$(md5sum "$file" | awk '{print $1}')
        temp_file=$(mktemp)
        response=$(curl -s -o $temp_file -w "%{http_code}" $download_api?filename=$file_name)
        if [ "$response" -ne 200 ]; then
            log_error $response $file_name
            rm -f $temp_file
            continue
        fi
        downloaded_md5=$(md5sum $temp_file | awk '{print $1}')
        if [ "$local_md5" = "$downloaded_md5" ]; then
            echo "Downloaded $file_name successfully and md5sum matches"
        else
            echo "Downloaded $file_name but md5sum does not match"
        fi
        rm -f $temp_file
    fi
done