Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

bash vs perl

by leocharre (Priest)
on Jan 11, 2008 at 11:16 UTC ( #661859=perlquestion: print w/replies, xml ) Need Help??
leocharre has asked for the wisdom of the Perl Monks concerning the following question:

Sometimes I code little scripts that do stuff, maybe i let them take arguments via the command line. Most of the calls end up being system calls, I use perl because .. Kinda feels right, checking the parameters passed in, etc etc.

I was considering that maybe I should look into just writing plain old bash for some of these.. So, how do we take parameters in bash.. aha.. simple enough, $1, $2, $3 are the positions of the arguments passed in broken up by spaces.

What if you want to use dash flag, like 'command -o val'

I thought.. this should be easy enough. And oh boy... Compared to perl's Getopt::Std.. . is bash getopts as much of an increible pain in the * as it looks like to be?? It's excruciating!

It seems that by comparison, bash is great if you know exactly what is going to happen, like, if you want to search your hard drive for empty directories and delete them- but if you want to do anything more intricate- you're looking for pain and anguish... My experience with bash is limited, so I may be having early rejection feelings.

Should one press on to experience it, getting more involved with bash then simple scripts?

Replies are listed 'Best First'.
Re: bash vs perl
by KurtSchwind (Chaplain) on Jan 11, 2008 at 14:16 UTC

    I think you hit a good example of when perl outpaces bash. If you are writing applications with options, bash is much harder and a lot less clean than GetOpt in perl.

    But I still think it's worth it to learn bash. Or more specifically, 'ksh'. The differences between bash and ksh are small, so think of ksh as the subset. (Off the top of my head, the main difference is forking a process during a while read.) At any rate, the reason shell programming is worth learning is because learning shell means learning unix commands. I'm astounded by the number of perl people that can navigate File:: cpan modules but can't write a decent find on the command line.

    Also, when you learn both, you get the best of both worlds. Your shell applications can call perl and vice versa. Mix and match as needed.

    I used to drive a Heisenbergmobile, but every time I looked at the speedometer, I got lost.
Re: bash vs perl
by davidrw (Prior) on Jan 11, 2008 at 15:02 UTC
    In general, just use the "right tool" for the job .. where that depends on the specific task and your knowledge/speed/ability in each, and relevant to that task..

    BUT, that doesn't mean one or the other -- use the power of both at the same time!! the perl -x (see perlrun) makes this possible (sort of a trivial example, but hopefully shows the potential):
    #!/bin/bash logrotate ..... # rotate out /data/file.txt perl -x $0 $@ > /data/file.txt 2>&1 mail -s "file.txt" < /data/file.txt echo "Job done. Errors:" grep ERROR /data/file.txt exit ####### #!/usr/bin/perl # do whatever perl-friendly tasks -- process some files, do calculatio +ns, call CPAN modules for heavy lifting, whatever.
Re: bash vs perl
by naChoZ (Curate) on Jan 11, 2008 at 15:12 UTC

    Actually it's very easy to use getopts from bash the way you're asking. This example would handle -a -b testval -c anotherval with the options a, b, and c.

    while getopts ab:c: FOO do case ${FOO} in a) BAR="somevalue" ;; b) BAR="${OPTARG}" ;; c) BAZ="${OPTARG}" ;; \?) echo "<some help text>" exit 1 ;; esac done

    The getopts ab:c: means that it's looking for -a, -b, -c and the colon after the b and the c means it expects a value to be specified for those params.

    So, while it's obviously not that difficult, it's also very, very limited and is vastly outstripped by perl modules like Getopt::Long. For example, you can only use single letters for your options. Sure, that's 24 available options which is plenty for most scripts, but what if you wanted to specify something like -min and -max. Suddenly you have to remember what letter you've assigned to what functions and it quickly becomes unwieldly.

    Check out my brief Getopt::Long example I posted over here recently.


    Therapy is expensive. Popping bubble wrap is cheap. You choose.

      Thank you for the example. Indeed when I saw these kinds of scripts to read three options, that's what made me gag.

      That's a *lot* of typing for three options. As I'm sure you know, compared to perl's 3 (three, tres) lines:

      use Getopt::Std; my $o={}; getopts('ab:c:defghijklmnop',$o); # map { printf "%s %s\n", $_, $o->{$_} } keys %$o;

      I disagree that single letter options are limited, in fact I throw a tantrum about that.
      '--min' in one cli app may be '--minimum' in another, we *know* that. So long notation doesn't really improve anything more then legibility, at least for the occasional user. Yes, yes.. then there are monsters like imagemagick convert.. good point, those need long.

      The only thing we can ever really be sure of is that hopefully us who code actually reserve -h for help, and that the documentation exists.

      The documentation is the authority for an interface. Some basic rules alway, yes.. options before file lists.. -h for help, -v for version, etc.. The user should *never* have to remember anything. Ever. -h, man, and info will tell them whatever they need to know.
      By the way, it's not 24, it's 52 or so, caps ! And I use them. And I document them. :-)

Re: bash vs perl
by apl (Monsignor) on Jan 11, 2008 at 13:59 UTC
    Stick with Perl. Sooner or later, you'll find yourself in a csh environment, or on a box running AIX or ... Small things will be different in each shell. Perl on the other hand remains consistant.

      (The following should be prefixed with a hearty "IMHO"; this is one of those areas where you'll need to get your fingers burned a couple times to internalize when you personally are on what side of the Perl/not-Perl divide . . .)

      Until you find a box still running Redhat 7.2 that's got an unpatched 5.005 that a third of the modules (or more) you need don't run on . . .

      So long as you're specifically targeting bash qua bash and not "generic Bourne shell" you're not going to have enormous portability issues. With either you're probably more likely to run into cases (if you don't have a specific environment under your direct control) where just getting your tool onto the boxen in question is than exotic portability concerns. Picking the implementation language that makes it easiest to get the problem solved should be given more weight over worrying if it'll run out of the box on a late-80s era 3b2 SysV box.

      (Having said that, Perl does have an advantage (to just name one, of course :) in that more is built-in to the language and you are more decoupled from environmental vagaries (e.g. does this box's stuff take strict POSIX options or GNU-y variants). But if all you need is to run 3-4 commands and glue together their inputs and outputs some form of shell might be the quicker answer; worst case you can always rewrite . . . :)

      Update: Couple minor additions and tweakings of wordings.

      Some links that may be of (possibly tangental) interest:

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

Re: bash vs perl
by shmem (Chancellor) on Jan 11, 2008 at 14:40 UTC
    Should one press on to experience it, getting more involved with bash then simple scripts?
    That depends greatly on one's job. A system administrator has to have proficiency with bash, /bin/sh or ksh, because /etc/rc* scripts, installers and the like are written in their languages. That didn't change since Tom Christiansen's Csh Programming Considered Harmful. Anything else? - stick with perl ;-)


    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: bash vs perl
by starX (Chaplain) on Jan 11, 2008 at 12:31 UTC
    First and foremost, have you tried Getopt::Long yet? I've never experienced anything resembling pain using that module to handle my CL args.

    Secondly, I'm sure there are a lot of monks here who use both Perl and Bash for doing simple tasks on a regular basis. I find that Bash syntax will be very limiting beyond doing simple things, though, and it is far less portable than Perl. Also, there's no such thing as :)

    In all seriousness, I doubt you'll find a task you can do in Bash that you can't do in Perl, but there's a lot of things you do in Perl that would be nearly impossible to do in Bash (alone).

    Update: corrected type.

Re: bash vs perl
by naikonta (Curate) on Jan 11, 2008 at 17:03 UTC
    My rule of thumbs: Whenever I feel like it, I'll write simple stuff with bash. If it takes 10 lines or so, it's not simple anymore (for me), so Perl takes over. If it takes command line switches, it's not something simple (for me) too, so Perl takes over as well. For simple switches I'll just use -s switch because it's simple and nice. However, for rather complex switches I'll turn to the standard Getopt::Long.

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

      Mine is similar: I'll use bash for simple sequences of shell commands, but, if it requires any logic beyond a couple simple if statements or loops, then it's time to switch to perl.
Re: bash vs perl
by sundialsvc4 (Abbot) on Jan 11, 2008 at 17:02 UTC

    Is there something particularly wrong with your power tools, that you suddenly want to start digging ditches with pick and shovel?

Re: bash vs perl
by sh1tn (Priest) on Jan 11, 2008 at 18:39 UTC
    The shell scripts are almost always slower and the code is neither readable nor compact.

    for i in `seq 1 10`; do touch $i; done

    Perl and derivatives
    perl -e 'open F, ">", $_ for 1..10'
    perl -e 'qx[touch $_] for 1..10'
    ruby -e '10.times{|i| i.to_s, "w"}'
    ruby -e '10.times{|i| %x[touch #{i}]}'

      touch and open '>' are hardly the same. You want utime

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://661859]
Approved by planetscape
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2018-11-14 20:30 GMT
Find Nodes?
    Voting Booth?
    My code is most likely broken because:

    Results (177 votes). Check out past polls.