How to get status code of previous command in Sublime-build "cmd"?

1

I want to use custom build commands for C source codes in Sublime Text 3. I am using the following code as sublime-build :

{
    "cmd" : ["gcc $file_name -o ${file_base_name} && konsole -e ''bash -c \"./${file_base_name}; echo 'Process returned $?'; read -p 'Press [ENTER] to exit.'\"''"],
    "selector" : "source.c",
    "shell": true,
    "working_dir" : "$file_path"
}

Here, the portion echo 'Process returned $?'; is causing serious problem (i.e. build doesn't run at all!) due to trying access to $?.

What is the alternative (or what is the right syntax) to use $? here ?

Chitholian

Posted 2018-05-12T10:58:45.763

Reputation: 67

Answers

0

$? in bash shows the exit status of the previous command.

$? is the correct syntax.

In an echo, if you use two '' $? wont execute and it will just echo '$?' instead of the exit status, you need to use "" instead.

The line echo 'Process returned $?'; should not cause a serious problem because it will just echo out what is between '' and ; just terminates the "line"

You're also not very consistent in your writing. Arent something like this what you are trying to achieve?

"cmd" : ["gcc {$file_name} -o ${file_base_name} && konsole -e 'bash -c \"./${file_base_name}';echo \"Process returned $?\";read -p 'Press [ENTER] to exit.'"],

I don't really see what you are trying to achieve with '\"''" at the end

Cristian Matthias Ambæk

Posted 2018-05-12T10:58:45.763

Reputation: 133

Your suggestion is fine but what I do badly need is keep the konsole window open. Your suggestion exits console window immediately after execution. – Chitholian – 2018-05-12T15:40:09.350

Have you checked if their is a option in the konsole command that lets it continue to be open? – Cristian Matthias Ambæk – 2018-05-12T17:53:57.127

0

The tricky point is correctly escaping the $ in $?, and all the nested quotes. And this is really a nightmare when you have such deep nesting:

  • cmd is defined as "..."
  • within that there is konsole -e '...'
  • within that there is bash -c "..."
  • within that there is echo '...' and read '...'

On top of that, you also need to account for Sublime's escaping rules, which makes writing this correctly a real nightmare, and impossible in a readable way.

Rather than trying to fix that, I recommend to extract the complex command into a script that takes $file_name and $file_base_name as parameters, like this:

"cmd" : ["/path/to/build.sh '$file_name' '$file_base_name'"],

Then, you can write /path/to/build.sh as any shell script, free of Sublime's parsing rules, and easy to test independently.

janos

Posted 2018-05-12T10:58:45.763

Reputation: 2 449