#!/bin/bash
# Dependencies:
# ------------
# xclip — read/write to clipboard
# jq — parse JSON
apiKey="" # Yandex API key, see here https://tech.yandex.ru/keys/get/?service=trnsl
firstLang=$1
lastLang=$2
text=$(xclip -o)
if [[ -z "$firstLang" ]]; then
firstLang='en'
fi
if [[ -z "$firstLang" ]]; then
lastLang='ru'
fi
if [[ -z "$text" ]]; then
# If clipboard is empty
notify-send Ooops... -i dialog-error "Nothing to translate."
else
# Sending request and parse JSON string
request=$(curl -sb -H "Accept: application/json" "https://translate.yandex.net/api/v1.5/tr.json/translate?key=$apiKey&text=$text&lang=$firstLang-$lastLang" | jq '.text[0]')
# Remove double quotes from a string
request=${request//\"}
# Sending notifications
notify-send Translate: -i edit-paste "$request"
# Copy the result to clipboard
echo "$request" | xclip -selection clipboard
fi
# How to use:
# ------------
# To use this script you need to assign it to run on hot keys. For example:
# ~/yandex-translate.sh en ru
# or:
# ~/yandex-translate.sh ru en
# Enjoy!