DEV Community

Cover image for bash ChatGPT
Peter Vivo
Peter Vivo

Posted on

bash ChatGPT

I often need to quickly ask ChatGPT something using a Linux/GitBash terminal, so I wrote this bash script to facilitate that. Main goal is terminal friendly output, without any additional dependency requirement for gitbash, so I used curl,sed and fold.

Image description

write to chatgpt.sh - do not forget your key!

#!/bin/sh
curl=`cat <<EOS
curl -sS --location --insecure --request POST 'https://api.openai.com/v1/chat/completions' \
--header 'Authorization: Bearer <OPEN_AI_KEY>' \
--header 'Content-Type: application/json' \
--data-raw '{
 "model": "gpt-3.5-turbo",
 "max_tokens": 2000,
 "messages": [{"role": "user", "content": "$1"}]
}'
EOS`
eval ${curl} | sed -En 's/.*"content": "(.*)"/\1/p' | sed 's/\\n/\n/g' | fold -s
Enter fullscreen mode Exit fullscreen mode

maybe add to ~/.bashrc some alias

alias ai='sh ~/chathgpt.sh'
Enter fullscreen mode Exit fullscreen mode

use

ai "write bash chatgpt call which give formated text result"
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Top comments (0)