Shell-To and standard error

New to Gambas? Post your questions here. No question is too silly or too simple.
Post Reply
JumpyVB
Posts: 75
Joined: Friday 11th September 2020 9:09am

Shell-To and standard error

Post by JumpyVB »

How to access standard error on shell calls?
Public Sub Form_Open()
  Dim Stdout As String
  Shell "ls /root/" To Stdout
  Me.Text = Stdout
  ' Stdout is "" (i.e. empty) 
  ' Where do I find the error which should be:
  ' "ls: cannot open directory '/root/': Permission denied"
End
User avatar
BruceSteers
Posts: 1559
Joined: Thursday 23rd July 2020 5:20pm
Location: Isle of Wight
Contact:

Re: Shell-To and standard error

Post by BruceSteers »

JumpyVB wrote: Sunday 23rd April 2023 10:09am How to access standard error on shell calls?
Public Sub Form_Open()
  Dim Stdout As String
  Shell "ls /root/" To Stdout
  Me.Text = Stdout
  ' Stdout is "" (i.e. empty) 
  ' Where do I find the error which should be:
  ' "ls: cannot open directory '/root/': Permission denied"
End

First use 2>&1 in the shell command to redirect stderr to stdout then use Process.LastValue to check for error value in last run process
Public Sub Form_Open()
  Dim Stdout As String

 ' First use 2>&1 to direct stderr to stdout

  Shell "ls /root/ 2>&1" To Stdout

  If Process.LastValue Then
   ' there was an error value so display the output text and Return
  Message.Error(Stdout)
  Return  
 Endif


  ' if error above then i did Return so if here there was no error and Stdout is no longer empty and should be a file list.

End


Note: only use this if using To or Wait with the Shell/Exec command so the process is not asynchronous and finishes before checking Process.LastValue or you may check the value of the previously run process.
If at first you don't succeed , try doing something differently.
BruceS
JumpyVB
Posts: 75
Joined: Friday 11th September 2020 9:09am

Re: Shell-To and standard error

Post by JumpyVB »

Thank you Bruce.
Post Reply