Ubuntu – How to check if gpg key already exist with bash then skip downloading/adding


So basically, I want to run these 2 commands but I want to check if the keys already existed. I know how to do the ifthenelse in bash but I'm not sure how to get the result and store in variable for me to check so that i can put it in the conditional operator. For example, if it already existed then I can skip downloading and adding it again.

Example 1 (–fetch-keys):

    sudo apt-key adv --fetch-keys https://packages.microsoft.com/keys/microsoft.asc
sudo tee /etc/apt/sources.list.d/vscode.list > /dev/null <<- END
    deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main

Example 2 (–recv-keys):

    sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys B9A06DE3
sudo tee /etc/apt/sources.list.d/inkscape.list > /dev/null <<- END
    deb [arch=amd64] http://ppa.launchpad.net/inkscape.dev/stable-daily/ubuntu bionic main

Best Answer

  • How about something like:

    TEST=$(apt-key list 2> /dev/null | grep my_app_name)
    if [[ ! $TEST ]]; then
        echo "Missing - need to run --fetch-keys or --recv-keys"

    I piped stderr into the null device ( 2> /dev/null ) to hide the warning you get for using apt-key list in a script.

    Try running "sudo apt-key list" on its own so you can see what the output looks like, in case you want to change the "grep" to be more selective.