简体   繁体   中英

How to get bash built in commands using Perl

I was wondering if there is a way to get Linux commands with a perl script. I am talking about commands such as cd ls ll clear cp

You can execute system commands in a variety of ways, some better than others.

  • Using system(); , which prints the output of the command, but does not return the output to the Perl script.
  • Using backticks (``), which don't print anything, but return the output to the Perl script. An alternative to using actual backticks is to use the qx(); function, which is easier to read and accomplishes the same thing.
  • Using exec(); , which does the same thing as system(); , but does not return to the Perl script at all, unless the command doesn't exist or fails.
  • Using open(); , which allows you to either pipe input from your script to the command, or read the output of the command into your script.

It's important to mention that the system commands that you listed, like cp and ls are much better done using built-in functions in Perl itself. Any system call is a slow process, so use native functions when the desired result is something simple, like copying a file.

Some examples:

# Prints the output. Don't do this.
system("ls");

# Saves the output to a variable. Don't do this.
$lsResults = `ls`;

# Something like this is more useful.
system("imgcvt", "-f", "sgi", "-t", "tiff", "Image.sgi", "NewImage.tiff");

This page explains in a bit more detail the different ways that you can make system calls.

You can, as voithos says, using either system() or backticks. However, take into account that this is not recommended, and that, for instance, cd won't work (won't actually change the directory). Note that those commands are executed in a new shell, and won't affect the running perl script.

I would not rely on those commands and try to implement your script in Perl (if you're decided to use Perl, anyway). In fact, Perl was designed at first to be a powerful substitute for sh and other UNIX shells for sysadmins.

The problem is perl is trying to execute the bash builtin (ie source , ...) as if they were real files, but perl can't find them as they don't exist. The answer is to tell perl what to execute explicitly. In the case of bash builtins like source , do the following and it works just fine.

my $XYZZY=`bash -c "source SOME-FILE; DO_SOMETHING_ELSE; ..."`;

of for the case of cd do something like the following.

my $LOCATION=`bash -c "cd /etc/init.d; pwd"`;

you can surround the command in back ticks
`command`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM