如何为curl中的localhost编写简写?实现curl 8000等效curl localhost:8000
改进后的zsh函数实现
可以通过遍历所有参数,区分curl的选项(带-前缀的)和非选项参数,同时跳过那些需要后续参数的选项(比如-o、-H等),找到符合纯数字(或数字加路径)的目标参数进行替换。以下是健壮的实现:
function curl() { local args=() local skip_next=0 for arg in "$@"; do if [[ $skip_next -eq 1 ]]; then args+=("$arg") skip_next=0 continue fi # 识别需要后续参数的curl常见选项,可按需补充 case "$arg" in -o|--output|-H|--header|-d|--data|-F|--form|-u|--user|-A|--user-agent|-e|--referer) args+=("$arg") skip_next=1 ;; *) # 匹配纯数字或数字开头带路径的参数,替换为localhost:xxx if [[ "$arg" =~ ^[0-9]+(/.*)?$ ]]; then args+=("localhost:$arg") else args+=("$arg") fi ;; esac done command curl "${args[@]}" }
关键说明
- 跳过选项关联参数:通过
skip_next标记,避免将-H后的头信息、-o后的输出文件名等选项附属参数误识别为URL进行替换。 - 灵活匹配规则:保留你原有的逻辑,纯数字(不限位数)或数字开头带路径的参数(比如
8000/api/v1)都会被替换为localhost:xxx。 - 兼容任意参数位置:不管目标URL参数在选项前还是后,都能正确识别并替换。
测试场景验证
- 直接执行
curl 8000→ 等效于curl localhost:8000 - 带请求头的情况
curl -H 'Content-Type: application/json' 8000/api→ 等效于curl -H 'Content-Type: application/json' localhost:8000/api - 带输出选项的情况
curl -o result.txt 8000→ 等效于curl -o result.txt localhost:8000 - 正常URL不受影响
curl https://example.com→ 执行原命令
内容的提问来源于stack exchange,提问作者cSharp
相关产品推荐
相关产品推荐

