Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash code injection into bash script
#!/bin/bash
# Bash code injection into bash script
# Copyright (c) Alexey Baikov <sysboss [at] mail.ru>
#
# This script will inject multiline code from 'injection.sh' file
# before or after a certain line in 'script.sh' file
#
# target_script - Script to inject into
# injection_script - Code lines to inject
# patern - Line to inject the code (before/after)
# Configuration
target_script="script.sh"
injection_script="injection.sh"
patern="Doing stuff"
# Let's initialize the files,
# just for demonstration
cat << EOF > script.sh
#!/bin/bash
echo "Starting the original script"
echo "Doing stuff..."
echo "Exiting"
EOF
cat << EOF > injection.sh
echo "Yay! It works!"
EOF
# create output file
output_file="${target_script}_injected.sh"
echo > ${output_file}
while IFS= read -r line
do
if [[ "${line}" =~ ${patern} ]]; then
# uncomment to past before the line
#cat ${injection_script} >> ${output_file}
echo "${line}" >> ${output_file}
# past after the line
cat ${injection_script} >> ${output_file}
else
echo "${line}" >> ${output_file}
fi
done < "${target_script}"
@sysboss

This comment has been minimized.

Copy link
Owner Author

@sysboss sysboss commented Jan 17, 2018

It's ugly, but it works 🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment