Skip to content

Instantly share code, notes, and snippets.

@ameiji
Last active May 18, 2025 23:41
Show Gist options
  • Select an option

  • Save ameiji/cb45127ea6b7cd4dc8c2a8036e667dba to your computer and use it in GitHub Desktop.

Select an option

Save ameiji/cb45127ea6b7cd4dc8c2a8036e667dba to your computer and use it in GitHub Desktop.
#!/bin/bash
# Download recent kubectl CLI versions
set -u
BIN_PATH="$HOME/bin"
RELEASES_URL="https://kubernetes.io/releases/"
OS=$(uname -o | tr -s '[A-Z]' '[a-z]' )
ARCH=$(uname -m)
WAIT_TIME=120
CONN_TIME=5
CURL_CMD="curl -s --connect-timeout $CONN_TIME -m $WAIT_TIME"
mkdir -p "$BIN_PATH" > /dev/null 2>&1
del_old_bins(){
local release=$1
local minor=$( echo $release | cut -d . -f 1,2)
old_bins=$( find . -type f -name 'kubectl-'${minor}'*' | grep -v "$release" )
if [ -s "$old_bins" ];then
echo "Deprecated: $old_bins"
mv -v $old_bins /tmp/
fi
}
pushd "$BIN_PATH"
# Check new version
$CURL_CMD -L "$RELEASES_URL" | rg Latest | rg -o '\d\.\d\d\.\d{1,2}' | sort | while read -r release; do
FILE_NAME="${BIN_PATH}/kubectl-${release}"
echo "=> Latest version is v${release}"
if [ -s "$FILE_NAME" ];then
echo OK
del_old_bins $release
continue
fi
# Download
echo "=> Downloading v${release}"
$CURL_CMD -sLo "$FILE_NAME" "https://dl.k8s.io/release/v${release}/bin/${OS}/${ARCH}/kubectl" || continue
# Create links
chmod +x "${BIN_PATH}"/kubectl*
LINK_NAME=$(echo -n $release | cut -d . -f 1,2 )
ln -f -s "$FILE_NAME" "${BIN_PATH}/kubectl-${LINK_NAME}"
del_old_bins $release
done
popd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment