lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Feb 25, 2014 at 09:14:10PM +0100, Petite Abeille wrote:
<snip>
> Looks reasonable enough, but with one gotcha: it never raises any exception when confronted with invalid commands:
> 
> lua - <<\EOF
> local aCommand = 'sqlite3 -bail | cat'
> local aHandle = assert( io.popen( aCommand, 'w' ) )
> 
> assert( aHandle:write( '.head on', '\n' ) )
> assert( aHandle:write( 'select count( * ) as count from sqlite_mister;', '\n' ) ) -- invalid table name
> print( aHandle:close() )
> EOF
> 
> > Error: near line 2: no such table: sqlite_mister
> > true	exit	0
> 
> What would be a reasonable way to capture the exit code of the initial command (sqlite3) as opposed to the piped one (cat)?
> 
> Is using PIPESTATUS reasonable enough?
> 
> 
> lua - <<\EOF
> local aCommand = 'sqlite3 -bail | cat; exit ${PIPESTATUS[0]};'
> local aHandle = assert( io.popen( aCommand, 'w' ) )
> 
> assert( aHandle:write( '.head on', '\n' ) )
> assert( aHandle:write( 'select count( * ) as count from sqlite_mister;', '\n' ) )
> print( aHandle:close() )
> EOF
> 
> > Error: near line 2: no such table: sqlite_mister
> > nil	exit	1
> 
> Seems to have the expected effect. 
> 
> Thoughts? Suggestions?
> 
> Thanks in advance.

There is also 'set -o pipefail' which will cause the return value of the
entire command to be the return code of the first failing command (or zero if
they all succeed) but PIPESTATUS gives you more control if you need more than
"did something in the command line fail and if so what was the final failure".

    -Etan