LoginSignup
4
3

More than 5 years have passed since last update.

iTunes のインターネットラジオで、現在流れている曲をテキストファイルに保存するシェルスクリプト

Last updated at Posted at 2013-09-24

シェルスクリプトの練習がてら作ってみました。
ここが変だよというものがあれば、是非聞かせてください。

songclip.gif

songclip.sh
#!/bin/bash
set -eu

# コマンド名を取得
declare -r COMMAND_NAME=$(basename "$0")

# ストリーム情報を保存するファイル
declare -r SONG_CLIP_FILE="$HOME/Dropbox/document/songclip.txt"

# iTunes からストリーム情報を取得
declare -r SONG_INFO="$(osascript -e '
  if application "iTunes" is running
    tell application "iTunes" to current stream title
  end if
')"

# コマンドの説明
usage() {
  cat << EOD
Usage: $COMMAND_NAME <subcommand>
  now       Display a current stream title
  list      Display the clipped song list
  delete    Delete the song info (only one line)
  purge     Purge the contents of existing file (delete all line)
  help      Display the Usage
EOD
}

# "missing value" か "" ならばエラーメッセージを表示して終了
check_stream() {
  if [ "$SONG_INFO" = "missing value" -o -z "$SONG_INFO" ]; then
    echo "Error: Can't retrieve the cunrent stream title."
    exit 1
  fi
}

# 引数の指定がない場合
if [ "$#" -eq 0 ]; then
  # 現在流れているストリーム情報をファイルに保存
  check_stream
  if grep -qs "$SONG_INFO" "$SONG_CLIP_FILE"; then
    echo "Now Playing the stream title is already exists."
    exit 1
  fi
  echo "$SONG_INFO" >> "$SONG_CLIP_FILE"
  echo "Clipped: $SONG_INFO"
  exit 0
fi

# 第一引数によって処理を分ける
case "$1" in
  "now")
    # 現在流れているストリーム情報を表示
    check_stream
    echo "Now Playing: $SONG_INFO"
    ;;

  "list")
    # 保存した情報を表示
    if [ ! -e "$SONG_CLIP_FILE" ]; then
      echo "$SONG_CLIP_FILE: No such file."
      exit 1
    fi
    cat -n "$SONG_CLIP_FILE"
    ;;

  "delete")
    # 入力された番号の行を削除
    echo -n "Please enter the line number: "
    read line_number
    expr "$line_number" + 1 >/dev/null 2>&1 | true
    if [ "${PIPESTATUS[0]}" -lt 2 ]; then
      file_rows=$(awk 'END { print NR }' "$SONG_CLIP_FILE")
      if [ "$line_number" -ne 0 -a "$line_number" -le "$file_rows" ]; then
        sed -i "" -e "${line_number}d" "$SONG_CLIP_FILE"
        echo "Deleted a line."
        exit 0
      fi
    fi
    echo "There is no such line. Please try again."
    exit 1
    ;;

  "purge")
    # ファイルを空にする
    echo -n "Are you sure you want to empty the file? (yes|no): "
    read purge_answer
    if [ "$purge_answer" = "yes" ]; then
      echo -n > "$SONG_CLIP_FILE"
      echo -n "." && sleep 1 && echo -n "." && sleep 1 && echo -n ". "
      echo "Purged the contents of the file."
    fi
    ;;

  *)
    # Usage を表示
    usage
    exit 1
esac

exit 0

上記はやや古いものですが、新しいものを GitHub にアップしました。
https://github.com/jamband/songclip

4
3
0

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
4
3