0

I am trying to generate a perl script and run it from a bash script, but I am running into issues:

#!/bin/bash
str="perl"
array=( one two three )
for i in "${array[@]}"
do
   str=$str" -e 'print \"$i \";'"
done
echo "$str"
echo "AND THE PERL OUTPUT: "
$str

generates the output:

perl -e 'print "one ";' -e 'print "two ";' -e 'print "three ";'
AND THE PERL OUTPUT:
Can't find string terminator "'" anywhere before EOF at -e line 1.

When I run the generated perl command perl -e 'print "one ";' -e 'print "two ";' -e 'print "three ";' manually, it works, but when I try to run it from the bash script, I get Can't find string terminator "'" anywhere before EOF at -e line 1.

Cannot seem to figure out where I am missing the terminator

3
  • Use set -x to see exactly what's being executed Commented Apr 3, 2020 at 20:08
  • AHA! exec -c perl -e ''\''print' '"one' '";'\''' -e ''\''print' '"two' '";'\''' -e ''\''print' '"three' '";'\''' Commented Apr 3, 2020 at 20:10
  • 1
    mywiki.wooledge.org/BashFAQ/050 Commented Apr 3, 2020 at 20:15

2 Answers 2

5

bash considers 'print as a single unit, it has found a opening ', but failed to find a closing one (string terminator).

This is a safer version :

#!/usr/bin/env bash

str=(perl)
array=( one two three )
for i in "${array[@]}"
do
   str+=(-e "print '$i ';")
done
echo "${str[@]}"
echo "AND THE PERL OUTPUT: "
"${str[@]}"
Sign up to request clarification or add additional context in comments.

Comments

1

Don't do this. Rather than fighting with a variable and all the parsing nightmare that creates, write it to a file and source it.

$: cat tst
#!/bin/bash
tmp=$(mktemp)
array=( one two three )
{ printf "perl"
  printf " -e 'print \"%s \";'" "${array[@]}"
  echo
} >| $tmp

printf "the script:\n===\n"
cat $tmp
echo "AND THE PERL OUTPUT: "
. $tmp
rm $tmp

$: ./tst
the script:
===
perl -e 'print "one ";' -e 'print "two ";' -e 'print "three ";'
AND THE PERL OUTPUT:
one two three 

But....why would you do this? =o]

3 Comments

If you're going to write it to a file anyway, wouldn't it make more sense to write the Perl script itself to a file, rather than writing a Bash command that runs the Perl script to a file?
this is just a test.. which is part of a larger bash file
@ruakh, hell yes, though sometimes it is admittedly easier to fold it all into one line if constructing programmatically. My thinking, on the other hand, is that if it complex enough to require Perl, it's time to rewrite the whole script in Perl.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.