[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Determine if a file is a valid Bash script
From: |
Eric Blake |
Subject: |
Re: Determine if a file is a valid Bash script |
Date: |
Mon, 19 Mar 2012 14:46:23 -0600 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:10.0.1) Gecko/20120216 Thunderbird/10.0.1 |
On 03/19/2012 02:15 PM, Stefano Lattarini wrote:
> On 03/19/2012 08:54 PM, Lane Schwartz wrote:
>> Hi,
>>
>> If I have a file that contains a bash script, is there any
>> straightforward way of determining whether that script can be parsed
>> successfully as a Bash script, without actually running the file?
>>
> Yes: the "-n" option. Simple examples:
>
> $ echo 'if :; then echo not seen; fi' | bash -n; echo status: $?
> status: 0
> $ echo 'if :; then echo not seen' | bash -n; echo status: $?
> bash: line 2: syntax error: unexpected end of file
> status: 2
Support for -n is required by POSIX for all sh-like shells. But it
comes with some caveats - on Solaris 8, the implementation of '/bin/sh
-n' is extremely inefficient, and can take several minutes on complex
scripts. And even older, on SunOS 4, you could make '/bin/sh -n' go
into an infinite loop on a script as simple a while loop that never
executes. More recently, modern ksh '-n' warns about every suspicious
construct, such as complaining about `` instead of $(). And don't ever
try 'set -n' in an interactive script or in the middle of a shell, as
you can't use 'set +n' to turn it back off :)
--
Eric Blake eblake@redhat.com +1-919-301-3266
Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature