bwobst
bwobst

Reputation: 351

Multiple 'exec' and 'print' commands in one file

Using a semicolon doesn't work when mixing exec commands and print commands.What is the best way to do this?

print "Initializing tests...\n"
print 'Testing 00_hello\n'
exec  'cd 00_hello; rspec hello_spec.rb; cd ..'
print 'Testing 01_temperature\n'
exec  'cd 01_temperature; rspec temperature_spec.rb; cd ..'

Upvotes: 1

Views: 1590

Answers (3)

Sachin Singh
Sachin Singh

Reputation: 7225

placing the string between backquote(`) will execute the string as system command.

for example try this.

print "Initializing tests...\n"
print 'Testing 00_hello\n'
`cd 00_hello; rspec hello_spec.rb; cd ..`
print 'Testing 01_temperature\n'
`cd 01_temperature; rspec temperature_spec.rb; cd ..`

Upvotes: 0

Linuxios
Linuxios

Reputation: 35788

You're mixing up exec with system. exec replaces the current process with running the command of the argument. If you want to run the file and wait for it and get control back, you need to use system:

print "Initializing tests...\n"
print 'Testing 00_hello\n'
system  'cd 00_hello; rspec hello_spec.rb; cd ..'
print 'Testing 01_temperature\n'
system  'cd 01_temperature; rspec temperature_spec.rb; cd ..'

Upvotes: 7

sepp2k
sepp2k

Reputation: 370435

If you're asking why the last two lines of your file won't execute, that has nothing to do with your use of semicolons. exec replaces the current process. Any code following a call to exec will not execute because the process stops executing as soon as exec is called. In most cases you want to use system, not exec.

I should also point out that it's not necessary to do cd .. at the end of a command given to exec or system. cd only affects the shell it is executed in and any processes spawned from that shell -- it does not affect the parent process. So if you cd inside a shell command, your ruby process won't be affected by that, so there's no need to cd back.

Oh and you can't use escape sequences like \n inside single quoted strings, they will just appear as a backslash followed by the letter n. You need to use double quoted strings if you want to use \n. If you use puts instead of print, it'll automatically insert a linebreak at the end, so you won't need the \n at all.

Upvotes: 6

Related Questions