How to Set up and Use ChatGPT in Linux Terminal

Leaving the popularity of NFTs and the metaverse in the dust, AI has emerged as the new buzzword in the technology world. ChatGPT and its alternatives are flourishing on the internet, helping users get everyday tasks done with ease. Earlier, we published guides on how to get started with making your own ChatGPT-like chatbot, using Bing AI in any browser, and more. But, what if you are a Linux user and want to bring the wits of this AI chatbot to your system? Well, this is where ShellGPT steps into the picture. It brings the power of ChatGPT right to your Linux Terminal. ShellGPT provides answers, intelligent suggestions, and writes commands and code for you, helping you navigate the command line efficiently. In this article, we will show you how to install the ShellGPT command line tool and use a ChatGPT-like AI bot in the Linux command line.

Run ChatGPT in Linux Terminal (2023)

What Is ShellGPT for Linux?

shellgpt linux
Image Courtesy: Farkhod Sadykov (Github)

Developed by Farkhod Sadykov (along with two other contributors, namely Eric and Loïc Coyle), ShellGPT is a command line version of ChatGPT that enables users to engage with the AI chatbot in their Linux terminal. It is based on OpenAI’s GPT large language model (read more about OpenAI’s new GPT-4 model right here).

ShellGPT can provide intelligent suggestions and recommendations and can even execute shell commands based on your text input. It also learns from your interactions and becomes more accurate over time. With this ChatGPT tool baked into the command line, users don’t have to type long commands or remember complicated Linux Terminal commands. They can save valuable time while minimizing errors, getting ChatGPT to do some of their menial work for them.

Prerequisites to Install ChatGPT in Linux CLI

Here are some of the prerequisites you need to fulfill before you can install ShellGPT on your Linux system. These are not too complicated tools and can be installed with some simple commands.

Install Python

Python is an indispensable tool, and like many other Linux tools and libraries, ShellGPT (command line version of ChatGPT) is also built on Python. In fact, ChatGPT is also built using Python along with other languages. Generally, Python comes preinstalled on most latest Linux distros. So first, check the python version installed on your Linux PC with this command:

python3 --version

python installed version check

If the above command outputs any errors, it means python is not installed or the deprecated python2.7 is installed on your system. Then, you can use our guide on how to install python in Linux.

Install Pip Package Manager

Pip is a cross-platform package manager for Python. It helps manage various Python packages and libraries required to bring ChatGPT to Linux. You can install, upgrade, and uninstall the required packages using a single command. It generally comes preinstalled with Python in most Linux distributions, but if it is not installed, you can install it with this command:

sudo apt-get -y install python3-pip

installing pip

Once installed you can check the Pip version installed in Linux with the following command:

pip3 --version

check pip version installed

Install Venv Module

This module is not necessary for ShellGPT or ChatGPT, but we recommend you install it to create an isolated virtual environment in Linux to prevent any conflict with other libraries. Installing any library or package will install many background dependencies that can interfere with other libraries. To create a virtual environment for a project, you need the “venv” module, which can be installed using the command below:

sudo apt install python3-venv

installing venv module

Set Up ShellGPT to Use ChatGPT in Linux Terminal

We have divided the instructions to install ShellGPT on your Linux PC into four different sections to make it easier for you to understand. Let’s start with setting up the environment, followed by getting the OpenAI API key, and installing the chatbot in the Terminal.

Set up the Environment

Now that you have the dependencies covered, let’s create the environment to access ChatGPT from your Linux terminal with the following steps:

1. First, open the terminal from the app menu or use the “Ctrl + Alt + T” keyboard shortcut.

2. Now, use the command below to create a new directory and keep all the files organized.

mkdir <your_directory_name>

For example, we have created a new directory with the name “commandline-chatgpt” with the command below:

mkdir commandline-chatgpt

How to Set up and Use ChatGPT in Linux Terminal

3. Then, switch over to the new directory you just created with the “change directory” command:

cd <new_directory_name>

In the example below, we have move to the commandline-chatgpt directory, where we will create the environment to use ChatGPT in the Linux terminal:

cd commandline-chatgpt

switching over to new directory - chatgpt linux

4. Now, use the command below to create a virtual environment with the venv module. We have used the “chatgpt_cli” name for our virtual environment.

python3 -m venv <virtual_environment_name>

For example: python3 -m venv chatgpt_cli

creating new virtual environment for ChatGPT in Linux

5. The virtual environment you just created will be deactivated by default. To activate the environment, use this command:

source <virtual_environment_name>/bin/activate

Once you execute the above command, the shell prompt will now display the name of the virtual environment in brackets, like this:

(<virtual_environment_name>)<username>@<system_name>

As you can see in the image below, the default Linux shell prompt changed to (chatgpt_cli) remote2@remotehost upon running the commands above.

activating virtual environment to install ChatGPT in Linux

Get Your OpenAI API Key

In order to use ChatGPT’s services in Linux, you will need an OpenAI API key. Currently, OpenAI is offering $5 credits for trial use. Once you exhaust the credits, you need to pay for access to the API. That said, here’s how you can get an OpenAI API key for this command line ChatGPT chatbot:

1. Navigate to OpenAI’s website (visit) and create a new OpenAI account. If you already have an account, simply log in and move to the next step.

2. Next, click on your profile image at the top right corner and select “View API keys” from the drop-down menu.

viewing OpenAI api keys

3. Here, you will see all the previously generated API Keys if any. To generate a new API key, click the “Create new secret key” button.

Generating new OpenAI API Keys

4. A new pop-up box will open with your API key. Do not share this API key with anyone or share it publicly. Copy your API key in a secure file or location, as you can only view it once. You won’t be able to copy the API key after you click “OK” here.

openAI API key - chatgpt linux

5. Now, create an environment variable for this API key with the command below. In Linux, you can create an environment variable using the “export” command. Replace <your_OpenAI_API_key_here> placeholder with the actual API key you generated to use ChatGPT in the Linux terminal.

export OPENAI_API_KEY=<your_OpenAI_API_key_here>

creating environment variable for OpenAI API Key

6. Verify the environment variable by listing it with the env command:

env

verify the environment variable for OpenAI API Key

7. This variable is only temporarily stored for the current session. To store the API key permanently, open the .bashrc file in the text editor of your choice and add the variable at the end of the file.

export OPENAI_API_KEY=<your_OpenAI_API_key_here>

adding the OpenAI api key to the .bashrc file - chatgpt linux

8. Save the file and exit the text editor after you have added the OpenAI API key. Now, run this command for the changes to take effect:

source .bashrc

9. Finally, verify the changes with the env command:

env

checking for OpenAI API Key inside environment variables

Install ShellGPT to Use ChatGPT

Having finished setting up the environment, you can now proceed to install the command line version of ChatGPT in Linux. You need to omit the –user flag if you are installing it in a virtual environment. Now, use the command below to install ShellGPT on your PC:

pip3 install shell-gpt --user

installing ShellGPT using pip - chatgpt linux

ShellGPT: Syntax & Options

Now that you have installed ShellGPT, you must be eager to use it for various tasks. But before that, let’s check out the syntax and some options that we can use to make our outputs interesting. Using ShellGPT for multiple tasks is easy, thanks to its straightforward syntax:

sgpt <options> <input_query>

Some of the options you can use with the ShellGPT (sgpt) chatbot are:

OptionDescription
--temperatureChanges the randomness of the output
--top-probablityLimits to only the highest probable tokens or words
--chatUsed to have a conversation with a unique name
--shellUsed to get shell commands as output
--executeExecutes the commands received as output from --shell option
--codeUsed to get code as output

How to Use ChatGPT in Linux Terminal (Examples)

1. Use ShellGPT for Queries

You can use ShellGPT as a search engine for any sort of query. Since it is an AI chatbot, you get results with more human-like answers and not a series of ranked web pages like most search engines. The syntax to use ShellGPT to get answers to your questions is:

sgpt "<your_query>"

For example, if you need to know the mass of the sun, use this command:

sgpt "mass of sun"

You see a nice animation in the Terminal while ShellGPT tries to get a response. The response we received is highlighted underneath. You might get a similar reply depending on how the model is trained:

The mass of the Sun is approximately 1.989 x 10^30 kilograms.

  • How to Set up and Use ChatGPT in Linux Terminal
  • How to Set up and Use ChatGPT in Linux Terminal

2. ChatGPT Chatbot Mode

If you had used ChatGPT for chatting, you must have felt that it is responses are no less than a human. Now with the help of ShellGPT, you can even use ChatGPT right from your Linux terminal. Simply use the --chat option followed by a unique session name and a prompt.

sgpt --chat <unique_chat_session_name> <input_prompt>

For instance, if you want to ask ChatGPT to tell you a joke, use this command:

sgpt --chat joke "can you tell me a joke?"

Once you run the above command, you will get the following result as output:

Sure, here's one:

Why couldn't the bicycle stand up by itself?

Because it was two-tired!
Chatting with ChatGPT from Linux terminal

3. Generate Code

You can even use the CLI-based ChatGPT tool to solve coding problems or generate code snippets. Simply use the --code flag to generate code for your prompt, as shown here:

sgpt --code "<input_prompt>"

For example, if you want to solve the classic Fizz Buzz problem using python, use this prompt:

sgpt --code "Solve classic fizz buzz problem using Python"

ChatGPT will quickly give you an output, which you can then paste into your code editor and test it out:

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
generating code for fizz buzz problem with ChatGPT in Linux Terminal

4. Generate Shell Commands

While the Terminal can be a powerful tool to execute complex commands and automate tasks, it can sometimes be difficult for novice users to remember the syntax and options of various Linux commands. With ChatGPT in your command line, you can not only get the syntax of a Linux command but also get the exact command with the parameters and options required. Simply use the --shell flag as:

sgpt --shell "<input_prompt>"

For example, if you need to set the read-only permission for all files in the current directory, use the command:

sgpt --shell "Make all files in the current directory read-only"

Generating Linux shell command using ChatGPT

As expected, ChatGPT delivers and returns this as the output:

chmod -R a-w .

Furthermore, if you use the --execute and the --shell flag together, you can even execute the shell command generated directly. As for the above example, here’s what the syntax looks like:

sgpt --shell --execute "make all files in current directory read-only"

executing the Linux shell command generated by ChatGPT

You will get the following output:

chmod -R a-w .
Execute shell command? [y/N]: y

Using ChatGPT in Linux Command Line

So yeah, ShellGPT brings the power of ChatGPT right into your Linux terminal. It not only makes working with the command line simple for both beginners and seasoned users but also brings you additional features. And as we mentioned above, it becomes more useful over time as it is designed to learn from users. But remember not to share any sensitive information or data, especially proprietary code from your company, with any kind of AI model. That said, do let us know what you think of this AI command line tool in the comments below.

comment Comments 22
  • Hi!

    I really wanted to have a Llama run on my cli in Linux. I tried a lot of options and spend a lot of time trying to catch a Llama. This article finally did it. Works perfect. Learned a lot in the process as well. Anyway thank you very much! Keep up the good work and goodbye!
    Frank

  • Hi, how do i enable a paid subscription after a trial has run out?

    Any help will be greatly appreciated.

    Thanks.

  • Thanks for these instructions….Im a mid-level linux guy that can apt-get with the best of them….

    I have followed these instructions several times to the letter (AFAIK) but when I run $sgpt “speed of fastest car” I get:

    ———————————————————————————————————————————————————–
    (chatgpt_cli) pi@mintop:~/commandline-chatgpt$ sgpt “speed of the fastest car”
    Traceback (most recent call last):
    File “/home/pi/.local/bin/sgpt”, line 5, in
    from sgpt import cli
    File “/home/pi/.local/lib/python3.10/site-packages/sgpt/__init__.py”, line 1, in
    from .app import main as main
    File “/home/pi/.local/lib/python3.10/site-packages/sgpt/app.py”, line 9, in
    from sgpt.config import cfg
    File “/home/pi/.local/lib/python3.10/site-packages/sgpt/config.py”, line 83, in
    cfg = Config(SHELL_GPT_CONFIG_PATH, **DEFAULT_CONFIG)
    File “/home/pi/.local/lib/python3.10/site-packages/sgpt/config.py”, line 40, in __init__
    self._read()
    File “/home/pi/.local/lib/python3.10/site-packages/sgpt/config.py”, line 73, in _read
    self[key] = value
    TypeError: unhashable type: ‘list’
    (chatgpt_cli) pi@mintop:~/commandline-chatgpt$
    ———————————————————————————————————————————————————–

    What am I doing wrong? Thx!
    Fred

  • how did you get a white block instead of the actual api key when running env?
    If I can get it to do that openai would be happy…ha ha
    spgt –chat install “how do I hide my api key?”
    it depends on …….. and went on and on with stuff that didn’t do anything.
    maybe you could teach chatgpt how….
    All in all this is the only tutorial that I got to work so kudos for that (:~)
    Sa Squatch

  • How can I add “source /bin/activate” to the executable file e.g. ‘sgpt’ to call this quickly from terminal?

    • You could go to your terminal settings and create a special GPT-Terminal. Just add the command as a startup command. You would also specify the startup directory in this instance. There are plenty of other ways to get this working for you…. ASK CHATGPT!

  • I had to drop the – -user flag in the install command, but it’s working great on my laptop running Mint Linux. Thanks for the tutorial.

  • I attempted the tutorial above on CentOS7.
    It seemed that all the process went quite smooth, but when I tried to execute: sgpt “mass of sun” – I got an error.
    Did anyone encountered this issue and have some insights?
    SSLError: HTTPSConnectionPool(host=’api.openai.com’, port=443): Max retries exceeded with url: /v1/chat/completions (Caused by SSLError(SSLCertVerificationError(1, ‘[SSL: CERTIFICATE_VERIFY_FAILED]
    certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)’)))

  • ChatGPT is an exciting development, but one of the examples shows how ChatGPT can produce unintended & destructive solutions:

    sgpt –shell “Make all files in the current directory read-only”

    This is an ambiguous command. Does it mean “the current directory” or “the current directory AND ALL SUBDIRECTORIES”? ChatGPT assumes the latter, executes a recursive command, and possibly destroys the permissions on large numbers of files that the user didn’t intend.

    Linux command-line options may be cryptic but they are precise. ChatGPT is not precise.

  • Sgpt “mass of sun”
    I’m getting an error saying something along the lines of too many requests
    It looks like a python error.
    The error happens no matter what. Even if I haven’t used the system in 24 hours. Note that chatgpt still works in the browser for me.

    • Same here, sgpt –shell –execute “make all files in current directory read-only”
      Also, is there any way to test that the installation is OK and this is in fact about too many calls?

  • `pip3 install shell-gpt –user` doesn’t work in the venv afaict. You need to drop the `–user`, which is what you did in the actual example by the looks. Other than that, good article. I just “translated” it to work on Fedora.

  • Great happening that! What all can AI do!!! Alas, what about the jobs of millions? Time to ponder by every human being. In fact, more the population, more the survival hammers!!!
    In any case, on the positive side, it helps a lot to set right issues faced by many, due to inefficient coders!!! Of course, opportunities for the coders to learn too!!!!

  • Attempted the tutorial given above on Ubuntu 22.04.
    2 LTS, x86_64 filesystem with 5.19.0-35 generic linux kernel. However, on executing the terminal command: pip3 install shell-gpt – -user,
    the following error in RED, is getting thrown up:
    “Can not perform a ‘–user’ install. User site-packages are not visible in this virtualenv AND
    http_error_msg= ‘401 Client Error:Unauthorised for url: https://api.openai.com/v1/chat/completions‘ + reason=unauthorised

    • Try installing the shellgpt package without the “`–user“` flag if you are working in a virtual environment with this syntax:
      “`
      pip3 install shellgpt
      “`

  • It was so insightful in knowing about this… thanks to whoever wrote this amazing article… great work!

Leave a Reply