Bash脚本带-d标志可下载 无标志时无法上传的问题求助
Bash文件上传下载脚本问题修复
问题描述
编写了一款基于transfer.sh的Bash脚本,核心功能为文件上传、下载:
- 使用
-d标志时可下载文件,示例命令:./script -d ./tests HJkv1I test.txt,此功能正常 - 不使用标志时应执行上传,示例命令:
./script test.txt test1.txt,但此场景下脚本无任何反应
原脚本代码:
#!/bin/bash fileUpload() { local filepath=$1 local transfer_path=$2 local url url=$(curl --progress-bar --upload-file "$filepath" "https://transfer.sh/$transfer_path") echo "$url" } printOutUpload() { local filepath=$1 local url echo "Uploading $filepath" url=$(fileUpload "$filepath") echo "Transfer File URL: $url" } fileDownload() { local destination=$1 local url=$2 local file_name=$3 curl -# "https://transfer.sh/$url/$file_name" -o "$destination/$file_name" } printOutDownload() { if [ $? -eq 0 ]; then echo "Success!" else echo "Error: There was a problem downloading the file." fi } while getopts "d:" opt; do case $opt in d) printOutDownload fileDownload "$2" "$3" "$4" ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; esac done
问题原因
- 缺少无选项分支逻辑:脚本仅处理了带
-d的情况,当没有任何命令行选项时,while getopts循环直接跳过,未执行任何上传相关代码 - 上传函数参数传递错误:
printOutUpload调用fileUpload时只传了1个参数,但fileUpload需要2个参数(本地文件路径、transfer.sh上的目标路径) - 下载逻辑参数传递错误:
getopts中-d分支里使用$2、$3、$4获取参数不可靠,且printOutDownload调用时机错误(在fileDownload之前,导致$?无法获取curl的执行状态)
修复后的脚本
#!/bin/bash fileUpload() { local filepath=$1 local transfer_path=$2 local url url=$(curl --progress-bar --upload-file "$filepath" "https://transfer.sh/$transfer_path") echo "$url" } printOutUpload() { local filepath=$1 local transfer_path=$2 local url echo "Uploading $filepath" url=$(fileUpload "$filepath" "$transfer_path") echo "Transfer File URL: $url" } fileDownload() { local destination=$1 local url=$2 local file_name=$3 curl -# "https://transfer.sh/$url/$file_name" -o "$destination/$file_name" } printOutDownload() { if [ $? -eq 0 ]; then echo "Success!" else echo "Error: There was a problem downloading the file." fi } # 处理命令行选项 while getopts "d" opt; do case $opt in d) # 移除已处理的选项,剩余参数为下载所需的目标路径、URL段、文件名 shift $((OPTIND - 1)) if [ $# -ne 3 ]; then echo "Usage for download: $0 -d <destination> <transfer-url-segment> <filename>" >&2 exit 1 fi fileDownload "$1" "$2" "$3" printOutDownload exit 0 ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; esac done # 处理无选项的上传逻辑 shift $((OPTIND - 1)) if [ $# -ne 2 ]; then echo "Usage for upload: $0 <local-filepath> <transfer-path>" >&2 exit 1 fi printOutUpload "$1" "$2"
关键修改点
- 添加无选项时的上传分支:在
getopts循环结束后,检查剩余参数并执行上传逻辑 - 修复
printOutUpload的参数传递:将第二个参数(transfer_path)传递给fileUpload - 修复下载参数处理:使用
shift $((OPTIND - 1))获取剩余参数,确保参数传递准确,并将printOutDownload移至fileDownload之后调用 - 添加参数数量检查:避免用户传入参数不足时脚本异常
内容的提问来源于stack exchange,提问作者Art
相关产品推荐
相关产品推荐

