You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bash中将两个入参不同的Shell脚本合并为单个可执行脚本

Shell多入参兼容镜像脚本合并方案

合并后的完整mynewfunc.sh代码

#!/bin/bash

# 非法参数提示
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
    echo "用法1(无域名限制镜像): $0 <目标站点URL>"
    echo "用法2(指定域名限制镜像): $0 <允许爬取的域名> <目标站点URL>"
    exit 1
fi

# 抽取公共wget配置,避免重复代码
wget_common_opt=(
    --recursive
    --no-clobber
    --page-requisites
    --html-extension
    --convert-links
    --restrict-file-names=windows
    --no-parent
)

# 按入参数量匹配执行逻辑
if [ $# -eq 1 ]; then
    target_url="$1"
    wget "${wget_common_opt[@]}" "$target_url"
else
    allow_domain="$1"
    target_url="$2"
    wget "${wget_common_opt[@]}" --domain "$allow_domain" "$target_url"
fi

使用说明

  1. 先给脚本加执行权限:chmod +x mynewfunc.sh
  2. 兼容两种调用方式:
    • 仅传1个参数(对应原f2.sh功能):./mynewfunc.sh https://example.com
    • 传2个参数(对应原f1.sh功能):./mynewfunc.sh example.com https://example.com/docs
  3. 若输入参数数量不对,会自动打印用法提示,不会执行错误命令

优化点说明

  • 公共配置抽成数组,后续调整wget参数只需修改一处即可同步到两种执行逻辑
  • 所有变量用双引号包裹,避免URL/域名中包含空格、特殊字符时出现解析错误
  • 增加参数校验逻辑,避免非法入参导致的异常运行

内容的提问来源于stack exchange,提问作者genggi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:54:05