curl 如果没有标志,脚本将无法运行

hgb9j2n6  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(135)

写了一个脚本,其主要任务是上传和下载文件.

#!/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

使用flag -d脚本从传输中下载单个文件:

./script -d ./tests HJkv1I test.txt

没有它应该上传文件:

./script test.txt test1.txt

一个接一个,这些函数都能正常工作,但是我不能让它们在一个脚本中工作-如果我添加-d标志,下载可以工作,但是上传不行,它什么也不做

ttcibm8c

ttcibm8c1#

在处理参数时设置一个标志。然后在getopts循环后,使用if语句根据标志执行上传或下载。

direction=up

while getopts "d:" opt; do
  case $opt in
    d) direction=down
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

shift (($OPTIND-1))

if [[ $direction == up ]]
then
    printOutUpload
    fileUpload "$@"
else
    printOutDownload
    fileDownload "$@"
fi

相关问题