Skip to content

Instantly share code, notes, and snippets.

@trappitsch
Last active April 8, 2024 14:48
Show Gist options
  • Save trappitsch/8b9fd5d9df2a665af964917d71ddb1b0 to your computer and use it in GitHub Desktop.
Save trappitsch/8b9fd5d9df2a665af964917d71ddb1b0 to your computer and use it in GitHub Desktop.
Bash script to copy binary into place

Bash script to copy binary into place from shell

This is a simple bash script that does the following:

  • Define an installation name and a path
  • Check if the user likes the default path or not
  • Check if installation / copy folder requires root access
  • Check if installation file already exists and if it does, ask if it should be overwritten
  • If all checks pass, the binary content below the line #__PROGRAM_BINARY__ are copied into the file at the given location and it is made executable

This bash script can be used to create a very simple installer for, e.g., a CLI tool. Modify the pathes you want to set as a default and the default name. Then save the file. Finally copy the binary data at the end. Let's assume your script is called my_installer.sh and the binary my_binary, the following will append the binary content at the end:

cat my_binary >> my_installer.sh

Enjoy!

#!/bin/bash
# Default installation name and folder
INSTALL_NAME=my_binary
INSTALL_DIR=/usr/local/bin
# Check if user has a better path:
read -p "Enter the installation path (default: $INSTALL_DIR): " USER_INSTALL_DIR
if [ ! -z "$USER_INSTALL_DIR" ]; then
INSTALL_DIR=$USER_INSTALL_DIR
fi
# Check if installation folder exists
if [ ! -d "$INSTALL_DIR" ]; then
echo "Error: Installation folder does not exist."
exit 1
fi
# Check if installation folder requires root access
if [ ! -w "$INSTALL_DIR" ]; then
echo "Error: Installation folder requires root access. Please run with sudo."
exit 1
fi
INSTALL_FILE=$INSTALL_DIR/$INSTALL_NAME
# check if installation file already exist and if it does, ask if overwrite is ok
if [ -f "$INSTALL_FILE" ]; then
read -p "File already exists. Overwrite? (y/n): " OVERWRITE
if [ "$OVERWRITE" != "y" ]; then
echo "Installation aborted."
exit 1
fi
fi
sed -e '1,/^#__PROGRAM_BINARY__$/d' "$0" > $INSTALL_FILE
chmod +x $INSTALL_FILE
echo "Successfully installed $INSTALL_NAME to $INSTALL_DIR"
exit 0
#__PROGRAM_BINARY__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment