I’m writing a shell script that before running needs to check that system Perl updates haven’t broken the Perl scripts being glued together. I keep getting what looks like a parsing error. To reproduce this on the command line:
$ module='Scalar::Util'; check="perl -e 'use $module' 2>&1"; check_status=`$check`; echo $check
Can't find string terminator "'" anywhere before EOF at -e line 1.
perl -e 'use Scalar::Util' 2>&1
Anyone see what I’m doing wrong?
Thanks.
Handling arguments with spaces in them like that is tricky at best; try to avoid doing so.
You should also use more vertical space; ‘one-liners’ is a derogatory term, not a term of approval.
You have:
The trouble is that when the shell processes:
it splits the string at word boundaries, yielding arguments:
Note that the I/O redirection is treated as an argument! To avoid the problem, in this context, you can use:
The
evalforces the shell to reparse the line, getting no errors.Be careful; simply using
evalis not always the solution to these woes. In particular, if you have backslashes, dollars or backticks around (or more quotes), thenevalcan simply compound the problems.One way of checking whether a module exists in Perl is:
That gives the module’s version number (and complicates the string). You can also simply do:
which will exit with status 0 if the module is loaded and spew forth errors etc if it is not.