How to Create Binary File from Shell Script


 While working with the Linux systems, we used many the commands on daily basis. Most of the commands are available in binary format in /bin, /sbin , /usr/bin, /usr/sbin, etc directories. As a system administrator or student we wrote many of shell script to do a few tasks or automate them. This article will help you to create a binary file of your shell script, so no one can see the source code of your script and we can use them as a command. To create a binary file from a script we use SHC compiler 

Follow the below steps to do this.

Step 1 – Prerequisites

First of all, You need to install the required packages for SHC compiler.

For Ubuntu, Debian, and LinuxMint

sudo apt-get install libc6-dev 

For CentOS, RHEL & Fedora

sudo yum install glibc-devel

Step 2 – Download and Install SHC

Download the latest source code of SHC compiler from its official webpage or use the below commands and extract into your system.

cd /usr/src
wget http://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.9.tgz
sudo tar xzf shc-3.8.9.tgz

Now compile the SHC source code on your system and install it using the following command.

cd shc-3.8.9
make
make install

Step 3 – Create Shell Script

Let’s create a shell script as per your requirement or skip this step if you already created it. For this article, we have created the below sample script which adds the integer values given on command line parameter and show the sum of them.

vim script.sh
#!/bin/bash

total=0

for i in $@; do
   if [ ! -z "${i##[0-9]*}" ]; then
	echo "Please enter numeric only"
	exit 1
   fi
   total=$(($total + $i))
done

if [ $total -eq 0 ]; then
    echo "Plesae execute script like: $0 10 20 30"
    exit 0
fi

echo $total

Step 4 – Create a Binary of Script

At this stage, we have installed SHC compiler and have a shell script named script.sh. Use the following command to create a binary file of your script.


shc -T -f script.sh

The above command will create two files in the current directory. One will be script.sh.x.c which is in C language format of your script. The second one will be script.sh.x which will be in binary format.

Step 5 – Test Binary Script:

If you try to open the binary format of the script, you will see that it is not in human-readable format.

Now move this script under /usr/bin directory to use from anywhere in system. Also remove .sh.x from file name. So it will be available with simple name. Also set the execute permissions to everyone

mv script.sh.x /usr/bin/script
chmod +x /usr/bin/script

Now type command ‘script’ from anywhere in the system. You will see the same results as your shell script does.

script 10 20 30 

60

Popular Posts