7

I am trying a code in perl script and need to call another file in bash. Not sure, which is the best way to do that? can I directly call it using system() ? Please guide/ show me a sample way.

from what I have tried so far :

     #!/usr/bin/perl
     system("bash bashscript.sh");

Bash :

#!/bin/bash
echo "cdto codespace ..."
cd codetest
rm -rf cts
for sufix in a o exe ; do
echo ${sufix}
find . -depth -type f -name "*.${sufix}" -exec rm -f {} \;
done

I am getting an error when I execute the perl script : No such file or directory codetest

syntax error near unexpected token `do

4
  • 1
    yes, you can using system("bash -c script.sh"), for example Commented Jul 24, 2012 at 18:07
  • @IgorChubin you're right , but if script has execution than bash -c is ok too Commented Jul 24, 2012 at 19:25
  • I solved my first problem according to stackoverflow.com/questions/255414/… : alias proj="cd /home/tree/projects/java" (Thanks to @Greg Hewgill) Commented Jul 24, 2012 at 21:48
  • Possible duplicate of How can I call a shell command in my Perl script? Commented Jul 25, 2019 at 10:54

4 Answers 4

11

If you just want run you script you can use backticks or system:

$result = `/bin/bash /path/to/script`;

or

system("/bin/bash /path/to/script");

If your script produces bug amount of data, the best way to run it is to use open + pipe:

if open(PIPE, "/bin/bash /path/to/script|") {
  while(<PIPE>){
  }
}
else {
  # can't run the script
  die "Can't run the script: $!";
}
Sign up to request clarification or add additional context in comments.

6 Comments

Good answer, but /bin/sh may not be bash, and if it is bash will run in --posix mode.
No reason to run sh just to launch bash: system("/bin/bash", "/path/to/script"); and open(my $PIPE, '-|', "/bin/bash", "/path/to/script") would avoid this.
also just `bash script.sh` could be used
@IgorChubin What does the $! do at the end of your code? I'm unfamiliar with Perl.
@IgorChubin Is the | necessary at the end of `"/bin/bash /path/to/script|")? What does that do?
|
1

You can use backticks to execute commands:

$command = `command arg1 arg2`;

There are several other additional methods, including system("command arg1 arg2") to execute them as well.

Here's a good online reference: http://www.perlhowto.com/executing_external_commands

Comments

1

You can use backticks, system(), or exec.

  system("myscript.sh") == 0
    or die "Bash Script failed";

See also: this post.

1 Comment

backticks in void context… use system() and save some extra work.
1

I solved my first problem according to Why doesn't "cd" work in a bash shell script? :

alias proj="cd /home/tree/projects/java"

(Thanks to @Greg Hewgill)

Comments

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.