For this example, I am creating a shell script to create another shell script that prints a specific message based on a template.
Template File Name : script-XXX.template
Content of the Template:
#!/bin/sh
# Simple Shell Script to Greet
echo Hello, XXX
XXX is the placeholder for replacement
Script File Name : scripter.sh
#!/bin/sh
echo Hello
- Set permision to script chmod
chmod 755 scripter.sh
- Execute script and verify it's functioning
>./scripter.sh
Hello
- In scripter.sh remove the echo Hello line and replace it with a
- variable to hold file name
- take a copy of template with file name (cp)
- set permision to execute it
#!/bin/sh
fileName=say-$1.sh
cp script-XXX.template $fileName
chmod 755 $fileName
- Use SED to replace place holder with desired value, in this case it's the same parameter
#!/bin/sh
fileName=say-$1.sh
cp script-XXX.template $fileName
chmod 755 $fileName
sed -i 's/XXX/'$1'/g' $fileName
- Now the script is complete. you can execute to create say-World.sh file and executes it.
>./scripter.sh World.sh
>./World.sh
Even though this will do the needful we can improve it little more
- Keep the template inside the scripter.sh itself by padding required lines in the output with some hashes(single hash marks line as comment) e.g. ###. Then we can read them using grep ( grep '###' ). This will read the line itself but with tail we can skip this ( tail -n +2 ) ( with $0 script can read it's name and $1-9 are command arguments)
- By checking the file exists we can avoid replacing existing files ( if [ -f $fileName ] )
- We can inline SED
- Fold lines if they are too long (only in console output)
- Then add nl to find line numbers
Final Script:
#!/bin/sh
fileName=say-$1.sh
if [ -f $fileName ]
then
echo
echo ------------------------------------------------------------------------------------
echo $fileName Exist if you want to replace it please delete the before executing this.
echo ------------------------------------------------------------------------------------
echo
exit 1
fi
echo --------------------------------------
echo Creating File : $fileName
echo --------------------------------------
echo Content:
echo --------------------------------------
grep '### ' $0 | sed 's/XXX/'$1'/g;s/### //g' | tail -n +2 | tee -a $fileName | nl | fold -w 100 -s
echo --------------------------------------
chmod 755 $fileName
echo
echo --------------------------------------
echo $fileName Created!
echo --------------------------------------
echo
### #!/bin/sh
### # Simple Shell Script to Greet
### echo Hello, XXX
- Comprehensive Tutorial on Shell Scripting https://www.shellscript.sh/