MST

星途 面试题库

面试题:Bash脚本中复杂命令行参数的解析与处理

编写一个Bash脚本,能够解析多个命令行参数,支持长格式(如 --verbose)和短格式(如 -v)选项,并且选项可以带有参数(如 --output=filename 或 -o filename),同时处理参数的顺序无关性。
26.9万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

verbose=false
output_file=""

while [[ $# -gt 0 ]]; do
    key="$1"

    case $key in
        -v|--verbose)
            verbose=true
            shift
            ;;
        -o|--output)
            if [[ $# -gt 0 ]] && [[ ${2:0:1} != "-" ]]; then
                output_file="$2"
                shift 2
            else
                echo "Option $key requires an argument."
                exit 1
            fi
            ;;
        *)
            echo "Unknown option $key"
            exit 1
            ;;
    esac
done

if [ $verbose = true ]; then
    echo "Verbose mode enabled"
fi

if [ -n "$output_file" ]; then
    echo "Output file: $output_file"
fi