4

I'm executing a script in lua:

os.execute("sh manager/scripts/update_system.sh" .. " " .. f)

And I want to get the output of the script( if exit status is 7 returns 7).

I tried

local output = os.execute("sh manager/scripts/update_system.sh" .. " " .. f)
print(output)

but it returns some weird numbers like 512

Any idea how to resolve this?

3
  • 3
    os.execute return values are different on 5.1 and 5.2 Commented May 23, 2014 at 10:51
  • @Egor Skriptunoff indeed! It was like "we've decided to completely change the function interface from int os.execute(string) to {bool,string,int} os.execute(string), so let's just do a minor version bump to warn the users that every single line of code that uses that function and perform error checking will crash." Commented Dec 18, 2020 at 17:58
  • @user1593842 - Minor Lua versions are incompatible. Actually, Lua 5.1 and Lua 5.2 are different languages, and it's not an easy job to migrate programs between the two versions. It is mentioned in the manual. Commented Dec 18, 2020 at 18:01

2 Answers 2

2

It seems like the outputs of os.execute are all 256 multiples. Don't ask me why, it must be a bug.

So I did this:

local exit = os.execute("sh manager/scripts/update_system.sh" .. " " .. f)
 local value = exit / 256
 print(value)

It works but I wonder if there is another solution.

Sign up to request clarification or add additional context in comments.

2 Comments

It isn't a bug. It is lua returning the raw value from system. See also wait for WEXITSTATUS.
As Egor said, os.execute has changed from lua 5.2 onwards. It now returns 3 value, and you can get the underlying process return code by looking at the third return value. However, it seems -- on Linux, at least --, that the return code is the same as what would "echo $?" provide (a value between 0 and 255). The third return value seems to be the return code, modulo 256.
-1

This works for both Lua 5.1 and Lua 5.2

exit_code = io.popen'your_command \necho _$?':read'*a':match'.*%D(%d+)'+0

1 Comment

JM2CW: I'd like to +1 but such one-liner obfuscates the answer. Code shown on SO should favor clarity over brevity. It should not be as condensed as the programming language will allow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.