LoginSignup
0
0

More than 1 year has passed since last update.

bashでcurlのオプションをたくさん指定する

Last updated at Posted at 2022-09-22

curlでファイルアップロードするシェルスクリプトを書いたときにつかった書き方。

コメントでいい方法教えてもらったので、そっちに書き換えた
echo "${args[@]}" するとダブルクォーテーションとか消えるので、不安に思ったけど実行すると確かにこれでできてるの不思議

#!/bin/bash

API_KEY="YOUR_API_KEY"
URL="https://example.com/endpoint"
SCRIPT_NAME=$(basename $0)
while getopts c: OPT
do
  case $OPT in
   "c" ) CONFIG_FILE=$OPTARG
      ;;
   *) echo "Usage: $SCRIPT_NAME [-c CONFIG_FILE] [FILES ...]"
      exit 1
      ;;
  esac
done
shift $((OPTIND-1))

if [ -f ${CONFIG_FILE:="$HOME/.myupload/config"} ]; then
  # アップするURLとAPIキーが書いてある
  source $CONFIG_FILE
else
  echo "$CONFIG_FILE is not exist." >&2
  exit 1
fi

# ファイルの存在確認。存在しないファイルが指定されたときは終了
declare -a FILES=()
for file in "$@"
do
  if [ -f $file ]; then
    FILES+=($file)
  else
    echo "$file is not exists." >&2
    exit 1
  fi
done

args=(-H "Authorization: APIKEY $API_KEY")
for file in "${FILES[@]}"
do
  args+=(-F "files[]=@$file")
done
curl "$URL" "${args[@]}"

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0