3

I have looked for this elsewhere but not able to find something that matches my requirements.

The template below is the one I need to use :

dn: uid=$1,ou=home,dc=chan,dc=com

objectClass: organizationalPerson

objectClass: person

objectClass: inetOrgPerson

objectClass: top

cn: $2

sn: $3

userid: $1

userPassword:

I need to script in such a way that populates the following fields $1,$2,$3,$4 with the input that I give it and then outputs to a new file thus allowing to run it using the blank template.

9

I suspect you are looking for something quite simple like a file my_script that contains:

cat <<XXX
dn: uid=$1,ou=home,dc=chan,dc=com

objectClass: organizationalPerson

objectClass: person

objectClass: inetOrgPerson

objectClass: top

cn: $2

sn: $3

userid: $1

userPassword:
XXX

To use the above, simply run:

sh my_script fred 100 200

which will output to stdout (and can be redirected to a file).

  • This gives me "my_script: 1: my_script: Syntax error: redirection unexpected" – Colin D Apr 5 at 16:48
  • 1
    I believe you mean to use two redirect arrows on the first line – Colin D Apr 5 at 16:48
  • 1
    And it took 3 years for someone to find that. Kudos! – Brian Apr 5 at 18:03
3

Does there actually need to be a template file?

#!/bin/bash

echo "dn: uid=$1,ou=home,dc=chan,dc=com" > $4
echo "objectClass: organizationalPerson" >> $4
echo "objectClass: person" >> $4
echo "objectClass: inetOrgPerson" >> $4 
echo "objectClass: top" >> $4
echo "cn: $2" >> $4
echo "sn: $3" >> $4
echo "userid: $1" >> $4
echo "userPassword:" >> $4

You would run ./SCRIPTNAME Value1 Value2 Value3 OutputFileName

otherwise

You script would be:

#!/bin/bash

var1=$1
var2=$2
var3=$3
file=$4

cat TemplateFile > $file

sed -i "s/1/$var1/g" $file
sed -i "s/2/$var2/g" $file
sed -i "s/3/$var3/g" $file

and your template file would be

dn: uid=1,ou=home,dc=chan,dc=com 
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: 2
sn: 3
userid: 1
userPassword: 
  • Ah I did this when yours was one string, hold on I'll fix it. – Kip K Oct 16 '15 at 17:22
  • Don't use repeated redirections. Rather than slapping ">> $4" on the end of each line, just do exec > $4 at the start. – William Pursell Jan 5 at 19:54
0

I solved similar problem with

elegant and short solution in one line with perl

Use perl to replace variables with their values:

export world=World beautiful=wonderful
echo 'I love you, $world! You are $beautiful.' >my_template.txt
perl -pe 's|\$([A-Za-z_]+)|$ENV{$1}|g' my_template.txt

The output: I love you, World! You are wonderful.

my_template.txt can contain variables prefixed with $.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.