MST

星途 面试题库

面试题:Bash脚本函数设计与错误处理模式

编写一个Bash脚本,包含一个函数,该函数接受两个文件路径作为参数,将第一个文件的内容追加到第二个文件中。要求在函数内处理文件不存在等常见错误,并以合适的方式反馈错误信息。
11.2万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

append_file_content() {
    local file1="$1"
    local file2="$2"

    if [ ! -f "$file1" ]; then
        echo "Error: The first file $file1 does not exist."
        return 1
    fi

    if [ ! -f "$file2" ]; then
        echo "Error: The second file $file2 does not exist."
        return 1
    fi

    cat "$file1" >> "$file2"
    if [ $? -eq 0 ]; then
        echo "Content of $file1 has been successfully appended to $file2."
    else
        echo "Error occurred while appending content."
        return 1
    fi
}

# 示例调用
append_file_content "file1.txt" "file2.txt"