#!/bin/bash # Bash code injection into bash script # Copyright (c) Alexey Baikov # # 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}"