Slashdot Mirror


Adding Some Spice To *nix Shell Scripts

An anonymous reader writes "Developing GUI script-based applications is time-consuming and expensive. Most Unix-based scripts run in a CLI mode or over a secure ssh session. The Unix shells are quite sophisticated programming languages in their own right: they are easy to design and quick to build, but they are not user-friendly in the same way the Unix commands aren't (see the Unix haters books). Both Unix and bash provide features for writing user friendly scripts using various tools to build powerful, interactive, user-friendly scripts that run under the bash shell on Linux or Unix. What tools do you use that spice up your scripts on the Linux or Unix platforms?"

411 comments

  1. Pashua on OS X by iliketrash · · Score: 3, Informative

    On OS X, I use Pashua, http://www.bluem.net/en/mac/pashua/. This is a brilliantly simple thing to use. I also use it for other (non-script) languages for making a quick-and-dirty GUI that still looks nice and is a real Cocoa program.

    1. Re:Pashua on OS X by FictionPimp · · Score: 1

      I've always used either straight apple script to make dialogs and call my bash scripts or I use apple script to call nib files made with interface builder and have that call my bash scripts. You can see an example of that here: http://tacticalcoder.com/blog/2009/05/accessing-remote-machines-via-ssh-with-finder/

    2. Re:Pashua on OS X by supssa · · Score: 0, Troll

      Pashua is Aqua, and Aqua has been deprecated for years now. Please move away from Pashua and work with a Cocoa interface.

      --
      Hatin' on products I don't like and getting modded up talking about tech I totally don't understand like it was 2005!
    3. Re:Pashua on OS X by Kooty-Sentinel · · Score: 1

      Don't hate on him. Look at his signature :)

      .....ducks and hides.

      --
      Your evaluation period for Productivity 1.0 has ended. Please purchase more coffee to continue using this product.
    4. Re:Pashua on OS X by iliketrash · · Score: 3, Interesting

      If you would get your facts straight there would be no need to flame.

      OS X has been UNIX 03 (SuSv3) registered and POSIX compliant since 2007.

      FYI, no version of Linux is registered Unix.

      Read these and learn:
      http://en.wikipedia.org/wiki/UNIX_03
      http://images.apple.com/macosx/technology/docs/L416017A_UNIX_TB_FF.pdf
      http://www.apple.com/server/macosx/technology/unix.html

    5. Re:Pashua on OS X by iliketrash · · Score: 2, Interesting

      Oh, where to start. Comparing Aqua to Cocoa is like comparing bananas to cars. Aqua is the name for the GUI components http://en.wikipedia.org/wiki/Aqua_(user_interface) and Cocoa is the preferred API http://en.wikipedia.org/wiki/Cocoa_(API). Aqua has not been deprecated, not now and not "for years." You can write OS X apps in Aqua using Carbon which _has_ been deprecated for years but is still fully supported. Many popular (and older) OS X programs still run in Carbon such as Quicken, Igor Pro, and at least until recently, Microsoft Office.

    6. Re:Pashua on OS X by Mister+Kay · · Score: 0

      Someone give this man a cookie.

    7. Re:Pashua on OS X by DocHoncho · · Score: 1

      YHBT. If you look closely at the username you will find it's very similar to a frequent Slashdot poster Sopssa (http://slashdot.org/~sopssa). This kind of crap goes on all the time. Some silly asshole got all butthurt about something Sopssa said and made an account with a similar name in order to trick people into thinking it's him. For shame. DO NOT FEED THE TROLLS!!

      --
      Celebrity worship is a poor substitute for Deity worship and costs more to boot.
    8. Re:Pashua on OS X by Anonymous Coward · · Score: 0

      I assume he's a joke account ragging on sopssa, who that sig definitely applies to.

    9. Re:Pashua on OS X by Anonymous Coward · · Score: 0

      Wish I could mod you up! I've been searching for this for years! (plural may be exaggeration.)

    10. Re:Pashua on OS X by Anonymous Coward · · Score: 0

      Why is parent flamebait? I just had a good great laugh... before taking my anti-depressants. Is miracle!

      Fanbois have no sense of humor.

    11. Re:Pashua on OS X by linuxpyro · · Score: 1

      I think a lot of distributions actually come fairly close, but the issue is the money. Since many distros are maintained by volunteers, if they had the cash for getting certified they probably would rather spend it on other things. Not sure why someone like RedHat wouldn't go for it, though.

      Then again I'm not sure how much it costs to get officially certified.

      --
      Saying "I'll probably get modded down for this" in a post is the best way to get it modded up.
    12. Re:Pashua on OS X by SolitaryMan · · Score: 2, Funny

      FYI, no version of Linux is registered Unix.

      Thank God for that!

      --
      May Peace Prevail On Earth
    13. Re:Pashua on OS X by iliketrash · · Score: 1

      I should have also mentioned CocoaDialog, http://cocoadialog.sourceforge.net/. My apologies. I haven't used it myself but I think that it could be combined to good effect with Pashua. My recollection is that there is some overlap but some differences. And the main approaches are probably different as well.

  2. None! by Anrego · · Score: 5, Insightful

    I know this is troll-ish, but the way I view it a script is just that.. a script. A series of commands to be executed in a specific order designed to automate a repetative task. Basic logic, control, and input are generally ok.. but interaction is in my opinion an indicator that your task is out of scope for a "script" and should become a full fledged application.

    (you may now freely argue amongst yourselves on the difference between a script and an application)

    There are a metric ass-tonne of dialog-type apps out there .. just google for your favorite toolkits prefix and "dialog" and you'll probably find something..

    gdialog
    kdialog
    xdialog
    etc..

    1. Re:None! by Anonymous Coward · · Score: 0

      Right on! Examples given in the second link are mostly for desktop 'scripts' - not your typical automated task scripts running on servers. (Not that they are useless - just that does not work for most of the scripted tasks).

    2. Re:None! by Antidamage · · Score: 2, Interesting

      Sometimes you just have too many flags to really want to be hammering things haphazardly into a single line. In that case guided scripts seem like a fine solution, too. Any simple frameworks out there to save reinventing the wheel?

    3. Re:None! by shawn443 · · Score: 1

      I don't know if I agree or disagree. I look inside my init.d and see complicated yet thoroughly worked out logic. I see interaction coming from the other moving parts with conditional statements. I consider these startup applications even if they are really just scripts. Gotta love /bin/bash though.

    4. Re:None! by Anonymous Coward · · Score: 0

      I would go with aliases for commonly used flags myself.
      My .bashrc, for example, contains:
      alias warez="rsync -vrhz --ignore-existing --progress --rsh=ssh"
      alias twarez="tsocks rsync -vrhz --ignore-existing --progress --rsh=ssh"

      This way I can do this easily ("warez : ." to download, "twarez" being for if I'm in college and need to use the socks proxy), this took about 30 seconds to set up and now requires just a short command and no knowledge of what the flags mean (I can't even remember tbh)

    5. Re:None! by CAIMLAS · · Score: 2, Interesting

      Often, I find myself writing scripts dealing with tasks which are semi-automated: I need a couple variables of input to deal with variance, but for the most part it's a repetitive task.

      What you're referring to is a batch script; that's good and fine, and I need those two. But that doesn't mean that interaction delineates a "script" from an "application".

      Though, I agree on one thing: a script is a script. There's no need to throw a dialog on there unless it in some way cleans up your input/output code and/or makes parsing the input cleaner.

      --
      ~/ssh slashdot.org ssh: connect to host slashdot.org port 22: too many beers
    6. Re:None! by grcumb · · Score: 2, Interesting

      I know this is troll-ish, but the way I view it a script is just that.. a script. A series of commands to be executed in a specific order designed to automate a repetative task. Basic logic, control, and input are generally ok.. but interaction is in my opinion an indicator that your task is out of scope for a "script" and should become a full fledged application.

      Well, there's interaction and then there's interaction. The grey area between script and application might be larger than your instinct tells you....

      I do document processing for large volumes of legal materials. A number of my scheduled tasks require graduated responses. If the task completes as desired, then no interaction is necessary. If the task encounters one of a set of known issues, then some sort of logic is necessary to decide whether it needs a technical remedy or whether an expert legal editor needs to intervene.

      Because the steps are somewhat malleable (we receive documents from 20 different countries), it makes sense to break the process down into a series of discrete stages. Perfect for scripted solutions. But because interaction with humans might be required at any stage, we also need something a little more receptive to input than a number of command-line parameters.

      My scripts get wrapped into a proper framework that formalises the way in which they're run, their interfaces to syslog and email, as well as allowing custom logic (in the form of callbacks) in parsing STDOUT and STDERR. They're still scripts, but they run in an environment that smells a lot like userland[*].

      ----------------

      [*] Yeah, I know.

      --
      Crumb's Corollary: Never bring a knife to a bun fight.
    7. Re:None! by ls671 · · Score: 1

      I tend to agree !

      The only thing I use mentioned in TFA is the "logger" command. Also, you can just send an email if something goes wrong.

      I use scripting and cron jobs specifically because I do not want to need to have a GUI running or to input any parameters interactively for the job to terminate properly. God I hate MS-Windows for that, it is always harder to write a batch file to automate a task in Windows than it is on Unix when possible at all on Windows. So why try to make my scripts more Windows like ?

      As you mentioned although, some might argue that scripts could be used to write more interactive applications.

      Heck, I think I have a few scripts meant to be used interactively and which prompt for input and the "read" command is fine ;-))

      $ read a
      hello
      $ echo $a
      hello
      $

      --
      Everything I write is lies, read between the lines.
    8. Re:None! by ari_j · · Score: 1

      My understanding of the parent was that his definition of a script revolves around it being automated, as in no user interaction. I agree with that. If there is a more complicated user interface than exceptional situations calling for a yes/no answer, then it should be programmed like an application and not like a script.

    9. Re:None! by Anonymous Coward · · Score: 2, Insightful

      A series of commands to be executed in a specific order designed to automate a repetative task. Basic logic, control, and input are generally ok.. but interaction is in my opinion an indicator that your task is out of scope for a "script" and should become a full fledged application.

      So if your script needs to just ask for a path or a couple inputs to create a configuration file, should you build an installation utility? What if the script is just to ask for how many days of log files to keep? Should we install xdialog or zenity in order to put a nice GUI around "How many days of log files should be kept (1 or more, 0 to disable cleanup)?"

      It's this simplistic view of scripting that causes such idiocy as:

            #!/bin/sh
            LOGDIR=/mnt/fileserver/database_logs
            cd ${LOGDIR}
            rm -rf *

          (And yes, the above was a real script that I've seen)

      You're perhaps confusing a script with a batch file.

    10. Re:None! by Anonymous Coward · · Score: 0

      Often, I find myself writing scripts dealing with tasks which are semi-automated: I need a couple variables of input to deal with variance, but for the most part it's a repetitive task.

      What you're referring to is a batch script; that's good and fine, and I need those two. But that doesn't mean that interaction delineates a "script" from an "application".

      Though, I agree on one thing: a script is a script. There's no need to throw a dialog on there unless it in some way cleans up your input/output code and/or makes parsing the input cleaner.

      When all we have is hammers, everything looks like nails. Something kept nagging at me, and you helped me find it. It's the fact that we call them scripts and expect to give no input. The cognitive dissonance we should all have is that our scripts expect to generate no dialog boxes, but ALWAYS expect to throw in argument $1 and/or $2. on demand every time that's run. That is exactly the input we claim not to need though most scripts aren't argumentless shortcuts. The CLI is our hammer, so we tend to think we never give input, though in reality we must provide dynamic values like the target hostname to remotely connect to, or the port number to telnet into, or how many times to loop while we wait for something. We enter those values EVERY SINGLE TIME.

      And yet, we come to slashdot with the entrenched misconception that it's more "comfortable" (the hammer talking) to actually
      1) bring up a shell to locate the binary of the script
      2) type the name of said script
      3) ensure we correctly enter the arguments: proper order AND whitespace are normally assured if a GUI separates AND labels fields for us to fill in.

      I had no idea that any of these tools / shortcuts existed, besides "kdialog" and bash's /dev/host/tcp communication services. I think we can't blame ourselves --none of this stuff is discussed in modern shell books, even as a footnote. They always assume that there is no GUI, and in case we run a terminal, something like tput should really, really be mentioned so we can write scripts for the non-technical Sales guy who must have read-only access to reports for our clients.

      To sum up, what we normally perceive as parameterless scripts for the sake of not needing GUI's in our daily life are just one-liners (the kind that delete the same temp file or 'killall' the known-to-misbehave app.) It is debatable whether static one-liners should be considered scripts. Nobody who writes them for DOS is really called a scripting guru, for example, even though MS has revamped the shell with quite a few tools and command switches that provide an OK level of CLI automation.

    11. Re:None! by Anonymous Coward · · Score: 1, Informative

      This is too awful. If the cd command fails, the rm will remove the current directory. Arg ! This style of writing gives me shivers down my back.

      At my work I struggled to explain that doing tar and gzip on two line is very bad practice to produce tar.gz files.

    12. Re:None! by Thiez · · Score: 1

      The awesome thing about scripts that only use the CLI is that it's easy to use them in other scripts. When your script expects a user to mess around with dialog boxes, that becomes much harder.

    13. Re:None! by Anonymous Coward · · Score: 0

      There are a metric ass-tonne of dialog-type apps out there

      So explain what's that ^^^^^^^^^^^^^^^^^^ in Imperial Arse-Tons?
      It is quite usual for a script to take arguments.
      In a GUI environment, why not ask for them in a GUI dialog generated by the script?
      I've scripted enough in the last 20 years to know that sh/curses, Tcl/TK and Perl/TK have plenty of uses,
      especially when a script is to be handed over to another (non-technical) user as a desktop tool.
      O' course, GUIs were a luxury when I were a lad... (cue Python-esque 4 Unixmen sketch...)

    14. Re:None! by hesaigo999ca · · Score: 1

      Not talking about Nix per se, but use windows environment, I do tend to agree though, i use the vs2005 to build an app to ask me a whole bunch of questions and also report back outcomes of scripts, to avoid the cmd shell, then also add some more user friendly stuff, but in the whole, at the bass, i use the app to execute batch files that can also be executed from command line, in stages and with parameters, saves me rewriting the whole thing if i need to wrap it up as external dll, or even if i need to call just a quick one time shot on a batch file, far from being the big app, but simple enough that an interface means even most non programming users can do my job for me if i am gone on vacation....

    15. Re:None! by starfishsystems · · Score: 1

      In case anyone needs to understand what's wrong with the above script, ask yourself what happens if there's a typo in the setting of LOGDIR.

      First, the cd command fails. That leaves the current directory unchanged. Probably it's the home directory of whatever user is running the script.

      Second, the rm command runs successfully in that directory. Ahem.

      Notice that this is a general problem with software behavior, not specific to scripts nor to GUI frontends to scripts. This problem is the reason why people advocate tools such as cfengine and puppet, on the theory that people should be writing as few scripts as possible to do scalable system administration.

      --
      Parity: What to do when the weekend comes.
    16. Re:None! by ls671 · · Score: 1

      this is scripting 101

      you should always do:

      rm -rf ${LOGDIR}/*

      or even better, when not sure ${LOGDIR} is set properly:

      if [ -e ${LOGDIR} ]
      then
      rm -rf ${LOGDIR}/*
      fi

      anyway, I archive log files so I only move stuff in scripts, eventually they are deleted on the archive hosts although...

      anyway rm -rf in scripts is risky at least, try rm *_log or rm maillog ; rm syslog ; etc...

      --
      Everything I write is lies, read between the lines.
    17. Re:None! by Anonymous Coward · · Score: 0

      So if your script needs to just ask for a path or a couple inputs to create a configuration file, should you build an installation utility?

      Why not? The majority of Ubuntu users would love that.

      Most people are chrooted to $HOME.

    18. Re:None! by Anonymous Coward · · Score: 0

      Jesus Christ, please. Just stop talking.

    19. Re:None! by SolitaryMan · · Score: 1

      Well, if you need to execute a lot of unix commands in your script and do something with their input/output -- shell script is the easiest way to do it. Filter the stream, generate command line -- pretty easy. However, when you need to ask user the thing or two, do some math, parse options or input file, things get ugly. This is why I often write python programs that generate shell scripts and then feed that output to shell.

      --
      May Peace Prevail On Earth
    20. Re:None! by LordAzuzu · · Score: 1

      Dear ol' VI!

  3. Just Bash? by DarkKnightRadick · · Score: 2

    Limiting yourself much? Also *nix != bash and bash != *nix though I imagine all shells share a host of similar commands.

    --
    "There is a way that seems right to a man, but its end is the way of death." Proverbs 16:25 (NKJV)
    1. Re:Just Bash? by hedwards · · Score: 1

      Just as long as you're not scripting in a c shell you should be relatively OK. The scripts I see tend to be in either Bash or Bourne, but I'm sure there's people that insist on using the Korn shell and other ones. The main problem is that when you get too far from the standard shells you run an increased risk that the shell has to be installed. Bash for instance isn't installed by default on FreeBSD, but Bourne is.

      It's not just the built ins it's how they're used, you don't want to be caught scripting in C shell as there isn't a proper way of seeing what the command is going to do ahead of time. You're also needing to worry about the quality and types of operations that the shell can handle. Some are more focused on scripting than others are.

    2. Re:Just Bash? by DarkKnightRadick · · Score: 1

      That's pretty much what I thought.

      Bourne is? IIRC csh is installed by default (I moved to tcsh on a recommendation and am pretty much loving it). This was FreeBSD-8.0-RELEASE

      I've never done much scripting (I've wrote a few, but that was years ago on bash (I've been out of the loop for a while and only recently started using FreeBSD)).

      --
      "There is a way that seems right to a man, but its end is the way of death." Proverbs 16:25 (NKJV)
    3. Re:Just Bash? by Anonymous Coward · · Score: 0

      Bourne is "sh" (In unixes dating from V7 (ie all of them)). bash is the Bourne Again SHell. csh might be installed by default in fbsd, but programming in csh is considered harmful. Use Korn instead.

    4. Re:Just Bash? by DarkKnightRadick · · Score: 1

      I switched to tcsh (and have had zsh recommended by others) on a recommendation from a trusted friend. I'll re-evaluate that once I can figure why my graphics card isn't sending info the monitor and not causing an error to be passed to the bios.

      --
      "There is a way that seems right to a man, but its end is the way of death." Proverbs 16:25 (NKJV)
    5. Re:Just Bash? by Anonymous Coward · · Score: 0
      Hmmm, you need to choose your friends more prudently. I would not hoist csh on any but my worst enemy. ;)
      1. bash or ksh for simple unixy onliner things.
      2. AWK for things that need purdy output and cifer'n. (That's cyphering or arithmetic for the over educated in the audience)
      3. TCL/TK for making the PHB come all over [him||her]self.
    6. Re:Just Bash? by starfishsystems · · Score: 1

      Don't forget to mention Tcl/Tk.

      Not only is Tcl/Tk a superior scripting language due to syntactical regularity and minimalism, not only does it provide native access to Unix commands, but it also provides event handling and a simple means to build a GUI if you want to wrap one around your script functions.

      --
      Parity: What to do when the weekend comes.
    7. Re:Just Bash? by DarkKnightRadick · · Score: 1

      Except we're talking about shells, not languages. (:

      --
      "There is a way that seems right to a man, but its end is the way of death." Proverbs 16:25 (NKJV)
    8. Re:Just Bash? by DarkKnightRadick · · Score: 1

      except awk and Tcl/Tk isn't a shell.

      tcsh, zsh, and csh are all shells. (:

      --
      "There is a way that seems right to a man, but its end is the way of death." Proverbs 16:25 (NKJV)
    9. Re:Just Bash? by ishobo · · Score: 1

      Tcl normally functions as a shell, hence why it is called as tclsh. It even supports an init file, history, and command line editing.

      --
      Slashdot - The great and glorious cluster fuck of Internet wisdom.
    10. Re:Just Bash? by ishobo · · Score: 1

      In its standard distribution, TCL is installed as a shell.

      --
      Slashdot - The great and glorious cluster fuck of Internet wisdom.
    11. Re:Just Bash? by DarkKnightRadick · · Score: 1

      ok, again I stand corrected. I've never heard of it as a shell.

      --
      "There is a way that seems right to a man, but its end is the way of death." Proverbs 16:25 (NKJV)
    12. Re:Just Bash? by DarkKnightRadick · · Score: 1

      that is a new one on me.

      --
      "There is a way that seems right to a man, but its end is the way of death." Proverbs 16:25 (NKJV)
  4. the usuals.... by girlintraining · · Score: 1

    sed, awk, grep, strings, lots of pipes, and randomly useful scripts made from them stuffed into my ~/bin folder...

    --
    #fuckbeta #iamslashdot #dicemustdie
    1. Re:the usuals.... by Anonymous Coward · · Score: 0

      heh.. What's the point? None of them send a message to user's desktop, do they?

    2. Re:the usuals.... by cynyr · · Score: 1

      "man notify-send" a way to make libnotify calls from just about anything, for that annoying pop up you feel you need.

      --
      All of the above was encrypted with a Quad ROT-13 method. Unauthorized decryption is in violation of the DMCA.
    3. Re:the usuals.... by RLiegh · · Score: 1

      What's the point? None of them send a message to user's desktop, do they?

      If you know that your user has a GUI, there's zenity which you can use to send a GUI message box to your user with.

    4. Re:the usuals.... by biryokumaru · · Score: 1

      None of them send a message to user's desktop, do they?

      heh.. What's the point?

      --
      When you're afraid to download music illegally in your own home, then the terrorists have won!
    5. Re:the usuals.... by Trogre · · Score: 1
      --
      "Nine times out of ten, starting a fire is not the best way to solve the problem." - my wife
  5. None, I have given up bash scripting by TheSunborn · · Score: 2, Interesting

    None, I have given up bash scripting. The syntax and semantic are simply to wierd. And it can't handle filenames with space in them without some serious hack magic.

    Maybe its time someone (re)-invent a total new shell, with a sane scripting language, commands with consistent names for the same arguments and in general something which don't feel like I live in 1980.

    And I am a fulltime linux used, and a software developer, and I do use the shell as an interactive interface, but I newer script it, and I always have the feeling that I am using a 20 year old interface with so many issues that its insane. Kinda like the same feeling I get when I use sas(The static package. Nice features HORRIBLE interface)

    1. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 2, Funny

      it can't handle filenames with space in them without some serious hack magic.

      Use quotes

    2. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      rc from plan 9 and/or unix v10

    3. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      "And I am a fulltime linux used,..."

      Me too, I always feel *used* by linux, although, I don't let it be fulltime.

    4. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Which is obvious :)

      Now, if you were talking about GNU make...

    5. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 3, Funny

      That's what novice "experts" usually say to do. Then you end up getting filenames that contain quotes. So what started as just escaping spaces turns into escaping spaces and two types of quotes. Depending on the approach you use here, you may need to escape some other characters, just in order to escape quotes, just so you can escape spaces, just so you can deal with filenames containing spaces.

      Any sensible person would say "fuck it" and just use a real scripting language like Python, Ruby or Perl.

    6. Re:None, I have given up bash scripting by Hatta · · Score: 4, Informative

      Does `find . -print0 | xargs -0` really qualify as "serious hack magic"?

      --
      Give me Classic Slashdot or give me death!
    7. Re:None, I have given up bash scripting by slimjim8094 · · Score: 1

      What's the problem with File\ Name.txt?

      --
      I have developed a truly marvelous proof of this comment, which this signature is too narrow to contain.
    8. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      In fairness, that doesn't fix what he's talking about -- handling filenames sent to and received from other processes (e.g. ls|grep something|sed ...)

      But that's not strictly a shell issue -- while most shells contribute, various other utils contribute as well. And, while more complicated than slapping quotes on, it's usually pretty straightforward to fix. More of an "oops, I forgot to take the usual precautions" than "how the fuck do I deal with this?!".

    9. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      MOD PARENT UP, BABY.

    10. Re:None, I have given up bash scripting by ZeBam.com · · Score: 3, Funny

      Use Perl

    11. Re:None, I have given up bash scripting by Sir_Lewk · · Score: 1

      The problems occur when you start writing scripts, and start passing filenames around in pipes and whatnot. Generally speaking there are ways to avoid doing that, but it's not uncommon to realize that you accidental put yourself in that sort of a situation.

      --
      "linux is just DOS with a UNIX like syntax" -- Galactic Dominator (944134)
    12. Re:None, I have given up bash scripting by Dadoo · · Score: 2, Insightful

      Use quotes

      Ummm... yeah. Try "tar tf file.tar | xargs rm", when some of the files in the archive contain spaces (or other shell special characters).

      --
      Sit, Ubuntu, sit. Good dog.
    13. Re:None, I have given up bash scripting by Grishnakh · · Score: 0

      Simple solution: don't use filenames with spaces in them. They're an incredibly stupid idea. If you need something that looks like a space, use an underscore. The same practice has been done in C since the early 70s, since having spaces inside C tokens would be stupid.

      The best way to write a script to handle a filename with a space is to make a two-line construct that determines if a file has a space, and if it does, exit with an error, telling the user to fix the filename.

      Most of these issues were resolves years (or decades) ago; it's only now with Windows and developers coming from the broken Windows platform that these issues are coming up again.

      The only reason you're having "so many issues" is because you're trying to apply a Windows mindset to Unix, as seen in your comment about spaces in filenames. All the stuff in Unix (and now Linux) has been built up over 40 years of use and development. Nothing's forcing you to use all the oldest methods, including bash scripting; you're perfectly free to use Perl, Python, etc. and never touch a bash script.

    14. Re:None, I have given up bash scripting by DaleGlass · · Score: 4, Informative

      Use:

      tar tf file.tar | xargs -d "\n" rm

      That will work unless the filenames contain newlines in them.

    15. Re:None, I have given up bash scripting by vux984 · · Score: 4, Insightful

      Simple solution: don't use filenames with spaces in them. They're an incredibly stupid idea. If you need something that looks like a space, use an underscore. The same practice has been done in C since the early 70s, since having spaces inside C tokens would be stupid.

      Simpler solution. Don't use computers.

      Seriously now. You expect all the end users out in the world to stop using spaces... just so your script works?

    16. Re:None, I have given up bash scripting by siride · · Score: 0

      I'm a big fan of Unixy goodness, but this post is retarded. If there is a problem along the lines of "I'm trying to do this totally legitimate thing XYZ, but language ABC is having trouble with it" and your answer is "don't do XYZ", you have not answered the question correctly. There is absolutely no reason why there shouldn't be spaces in filenames...except that certain old programs and scripts can't handle it. Well, some old programs and scripts can't handle property security either. Should we get rid of property security? No. Fix the programs. Similarly, fix the shell. Or...just use Perl or Python. But the solution is not "don't use spaces".

    17. Re:None, I have given up bash scripting by Cougar+Town · · Score: 1

      One thing that really pisses me off is scripts or apps that can't handle spaces or other certain characters in filenames.

      It's 2010. We have all kinds of advanced, powerful software, and a space is a perfectly valid filename character (unlike the C tokens you mention, where they are not actually allowed).

      Forty years ago we had two-digit years and other restrictions that were acceptable at the time. Well, it's not forty years ago, and things have come a long way. UNIX and UNIX-like systems can handle Unicode and lots of other technologies that were unheard of or in limited use forty years ago. Something as simple as spaces in filenames should be no exception.

    18. Re:None, I have given up bash scripting by CAIMLAS · · Score: 4, Insightful

      You mean something like perl? Or maybe python?

      My vote is for perl. It's more common in a "base install" than any other shell (in the BSDs and most Linux distros) and has a non-trivial amount of power. It's good at dealing with path and input permutations and you can interface it with pretty much anything. Hell, pcre came from perl, and that's used almost everywhere these days: it's got a lot of things right for the little that's wrong, at least in terms of being a good scripting language.

      I avoid "shell" scripting (csh, sh, bash) if at all possible, too. The contortions necessary to do the frequently-necessary evaluations takes quite a bit longer, even with a chain of awk/sed/grep and the like. Unlike those languages, perl is entirely self-contained and does not have any system-specific oddities (eg. with a shell script, many system binaries are different and an option/parameter pair on one system might do something entirely different on another - or not work at all).

      I realize perl can often (usually) be difficult to read. But for my purposes, it's good enough, because I'm a bit of a prolific comment writer as a matter of process.

      --
      ~/ssh slashdot.org ssh: connect to host slashdot.org port 22: too many beers
    19. Re:None, I have given up bash scripting by Grishnakh · · Score: 0, Troll

      No, I expect competent programmers to not do incredibly stupid things, like use filenames with spaces in them. There is absolutely no good reason for it, and tons of reasons against it (including the fact that CLI shells on both Unix and Windows interpret spaces as a field separator).

    20. Re:None, I have given up bash scripting by Cougar+Town · · Score: 2, Insightful

      I expect competent programmers to not be lazy and properly escape/sanitize their inputs.

    21. Re:None, I have given up bash scripting by hkz · · Score: 1

      tar tf file.tar | while read file; do rm "$file"; done

      This works because the entire line is read into $file, spaces and all.

    22. Re:None, I have given up bash scripting by Grishnakh · · Score: 1

      It's 2010. We have all kinds of advanced, powerful software, and a space is a perfectly valid filename character (unlike the C tokens you mention, where they are not actually allowed).

      No, while it may be technically valid, it's no more a good practice than embedding various high-ASCII characters (like #s 179-223) in your filenames. It just makes it extremely difficult for people to retype those things.

      Most unicode characters are not used as field delimiters. Spaces are. That's the reason they shouldn't be used, neither on Unix nor on Windows (try opening a DOS shell on XP and typing in a command using a filename with spaces, without quotes).

    23. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Then start reading man pages. You would be surprised what magic you can do with simply adding "xargs -0" and such. To me, you look like somebody who uses tool they know rather than using what's appropriate. Fulltime or not, yours is problem of attitude and aptitude.

    24. Re:None, I have given up bash scripting by hedwards · · Score: 1

      Spaces are a pain, but having witnessed how broken some OSes are when it comes to handling anything beyond the most basic, the advice I give is deviate from the extremely basic at your own risk. As far as I know all modern OSes can handle spaces in file names. But, it's better not to anyways. It's not that hard to end up in a situation where you've got illegal characters in the filename. I remember a while back trying to put my MP3s in a NTFS disk and having to deal with the several ? that the program had put into some filenames. The OS I did that on was fine with it, but when I got to Windows it was impossible to delete or really work with.

      If you use them then you need to account for them in some fashion. You can do it anyways, you just end up with more complication and another way in which things can go wrong.

    25. Re:None, I have given up bash scripting by Grishnakh · · Score: 0, Redundant

      I already showed the fix for it: make the script error out when it encounters a filename with a space in it.

      And you're wrong, there IS a reason spaces shouldn't be in filenames: spaces are used as field delimiters. Anything that comes after a space on a command line is supposed to be an additional argument. This holds true in both Unix and Windows, so it's not some kind of "archaic" Unix thing.

    26. Re:None, I have given up bash scripting by Grishnakh · · Score: 0, Troll

      As I said before, I already provided a solution: error out when encountering broken filenames like this. A two-line test is all that's needed. There is absolutely no good reason to have a space in a filename. Enabling bad practices only allows these practices to continue, just like enabling freeloaders by giving them what they want will only cause them to continue freeloading instead of getting a job.

    27. Re:None, I have given up bash scripting by DiegoBravo · · Score: 1

      > No, I expect competent programmers to not do incredibly stupid things, like use filenames with spaces in them.

      It is really difficult to find programs that create file names with spaces on purpose.

      The problem is that computers are used by..... people! and you know, people is used to spaces to separate words, so the file names will also carry that hideous defect.

    28. Re:None, I have given up bash scripting by Dadoo · · Score: 1

      Doggone it! You'd think, after 25 years of Unix, I'd know about that option. That's a good one. Thanks.

      I guess I'll have to read the man pages a little more often.

      --
      Sit, Ubuntu, sit. Good dog.
    29. Re:None, I have given up bash scripting by Darinbob · · Score: 1

      I've felt that sh (bash or ksh) is one of the more sane scripting languages out there, for what it does. Granted it's not a full programming language in many respects. Most of the oddities come from it being specially a scripting language for "commands" as well as the interactive command processor in one. Ie, Perl may be more powerful, but it would be inconvenient to use Perl as your CLI. There's a big difference between a programming language that lets you run a command as an afterthought and a command line shell that makes running commands be transparent while allowing you to build up complex sequences and scripts from the command line or a file.

      On the other hand, csh is pretty awful for scripting purposes. I think a lot of people get exposure to that and then run in fear from any Unix shell scripting in the future.

      Of course there are some things I'd probably change in sh, but of all the ugly CLI languages out there I like it best. Simple syntax, simple to use, doesn't get in your way, uniform interface to all commands, etc.

      File names with spaces are NOT an issue with sh itself, but an issue with the user or OS that created files with spaces in them in the first place. When you use an element delimiter within elements themselves, you're going to have to quote them somehow. This is sort of like complaining that C doesn't allow you to use spaces within variable names... If xargs gets confused, the problem is with xargs and not sh (and xargs does have ways to work around this).

    30. Re:None, I have given up bash scripting by KingKaneOfNod · · Score: 1

      I always have the feeling that I am using a 20 year old interface with so many issues that its insane

      Are you sure you're not using windows?

      Try writing batch files in windows then you will appreciate bash a bit more. Yeah I know - bash is a bit archaic, but it's a hell of a lot better than some of the alternatives.

    31. Re:None, I have given up bash scripting by hduff · · Score: 1

      As I said before, I already provided a solution: error out when encountering broken filenames like this. A two-line test is all that's needed. There is absolutely no good reason to have a space in a filename.

      That bon mot is little help when you have to deal with filenames that contain spaces.

      Enabling bad practices only allows these practices to continue, just like enabling freeloaders by giving them what they want will only cause them to continue freeloading instead of getting a job.

      The "fsck 'em -- just error out" and " Go away -- you're stupid" mindset is part of what gives UNIX a bad name in general. UNIX is not free of horrible programming practices; no OS is. And there have been some awkward choices in the past 40 years.

      Until all that stuff is fixed, you might want to STFU unless you want to grab the source code and fix it. And if you wrote it . . .

      --
      "I believe in Karma. That means I can do bad things to people all day long and I assume they deserve it." : Dogbert
    32. Re:None, I have given up bash scripting by camperdave · · Score: 1

      No, I expect competent programmers to not do incredibly stupid things, like use filenames with spaces in them.

      So you expect computers only to be used by competent programmers? In my world there's about 1 competent programmer to every 5000 or so regular users. You've got to expect spaces in your filenames.

      --
      When our name is on the back of your car, we're behind you all the way!
    33. Re:None, I have given up bash scripting by WeatherGod · · Score: 3, Funny

      Use Python

    34. Re:None, I have given up bash scripting by TheSunborn · · Score: 1

      I think that just illustrate the point that Bash have nice features but horrible syntax and magic.

    35. Re:None, I have given up bash scripting by kangsterizer · · Score: 1

      i find it simple:

      it's a simple task and can do it in 10-20 lines of bash or your favorite scriptable shell language? go ahead there won't be much quicker (usually its more like 3 lines rly)
      need more than 20 lines or lot of arrays and manipulations? don't do it. use another language. there's many. like python.

    36. Re:None, I have given up bash scripting by kangsterizer · · Score: 1

      or use python so non-perl ppl can still figure out what its doing :P

    37. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      double quotes are not a horrible hack

    38. Re:None, I have given up bash scripting by Interoperable · · Score: 1

      Bash's strength lies not in it's awkward syntax and idiosyncrasies, it lies in the ease with which bash passes arguments to other programs and grabs the return values. In a few lines bash can call precisely the tools needed and string together some very powerful tools. Sure, similar things exist in python and can be accessed easily. but you can't eek out the same flexibility or succinctness as you can with bash for many tasks.

      Unsurprisingly, the place where the *nix collection of tools shines in text manipulation. If you know bash, grep, sed, awk, sort and curl you're in good shape. Unless your filenames contain spaces, then you should know what $IFS does.

      --
      So if this is the future...where's my jet pack?
    39. Re:None, I have given up bash scripting by Ajaxamander · · Score: 2, Interesting

      From my understanding, the reason it's called "My Computer" in Windows is to force (lazy) programmers to handle spaces in file paths. But that could just be a rumor.

    40. Re:None, I have given up bash scripting by Grishnakh · · Score: 0, Troll

      That's why you error out when you encounter such a file.

      Plus, we're talking about bash scripting here, not C++ GUI application programming. How many "regular users" are using bash scripts from the command line? Since working with space-laden filenames is a PITA in the bash shell, I would expect any users who normally work at the command line to not be using such filenames.

    41. Re:None, I have given up bash scripting by Culture20 · · Score: 1

      it can't handle filenames with space in them without some serious hack magic.

      What's the problem with File\ Name.txt?

      Hacker! Hacker!

    42. Re:None, I have given up bash scripting by Darinbob · · Score: 2, Informative

      Because people want to use illogical syntax like "copy this file that directory" and have the shell figure out if this is referring to 4 different file names, or 3, or 2, or 1. Well actually they want to do slightly more sane things like "copy $file $dir" form a script, while expecting the shell to be smart enough to realize that the spaces in a command line are delimiters while at the same time the spaces in a variable's contents are not delimiters.

      Some command languages handle ok (ie, DCL, DOS) because they have each individual command parse its own command lines or expand variables. But sh expands all arguments before passing them to the commands; which is a logical and consistent way of processing arguments and there's nothing broken about it. Making all command uniform makes for easier shell scripting. Sure it means that sometimes you have to do extra work when you've got spaces in file names, but that isn't the fault of 'sh' but the fault of whoever shoved spaces in the file names in the first place.

      Like any programming language so far, you're always going to bump into "do what I mean not what I wrote" problems.

    43. Re:None, I have given up bash scripting by tzot · · Score: 2, Insightful

      So you've never reset IFS (or set it to a newline or tab) in your shell scripts? Your scripts just bail out instead of handling perfectly valid filenames? Because they are valid.
      You seem to transform the weakness of shell programs into an O/S guideline, and preach to that effect.

      --
      I speak England very best
    44. Re:None, I have given up bash scripting by Rudd-O · · Score: 2, Insightful

      Twenty years ago, the shell creators gave you the ability to enclose $VARIABLES in "$QUOTES". Methinks you BELIEVE you know how to script bash, but you have not really learned anything beyond typing commands in an interactive shell. Shell quoting is just so fundamentally obvious and they are mentioned so early in the bash manual, I have a REALLY HARD time believing you are a competent software developer (unless you program mirc scripts or in visual basic).

      --
      Rudd-O - http://rudd-o.com/
    45. Re:None, I have given up bash scripting by ae1294 · · Score: 2, Funny

      Use emacs. It's the best of all worlds...

    46. Re:None, I have given up bash scripting by Darinbob · · Score: 1

      No, but the conflict here is in assuming that sh is broken because it uses spaces as delimiters. The answer is that if the script doesn't handle file names with spaces in them, then fix the damn script!

      If you were using a different language, say perl, you'd be putting quotes around all the file names. That works in sh as well.

      Then there's the problem with file names that have quotes in their names, or file names that have carriage returns in their names, etc. Or even file names that have embedded scripts in their names designed to gain root access...

    47. Re:None, I have given up bash scripting by Darinbob · · Score: 1

      No, you don't need to fix the shell because of old broken scripts. Step one would be to fix the old broken scripts!

    48. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Hahaha.  You really have NO IDEA what you are talking about.  If the contents of a variable have a doublequote, NOTHING BAD HAPPENS when you use that variable *as long as you are consistent in quoting it*.  Everything works out just fine, does just what it is supposed to do.  I am pretty sure you won't understand one shit of what I am about to show you, but those who have a clue will, and it will prove you completely wrong:

      http://pastebin.org/160214

      I am surprised at the amount of incompetents who share their ignorant opinions on topics they know too little about.

    49. Re:None, I have given up bash scripting by Rudd-O · · Score: 1, Troll

      It does, for people who know 0.1% of what they use, but believe they know 90% and have strong opinions (that would be the person you are replying to).  GIVE HIM DA CODEZ TO HACK!  Hahaha!

      --
      Rudd-O - http://rudd-o.com/
    50. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      The Unix shell started in 1969. And it had it plumbing by 1972.

    51. Re:None, I have given up bash scripting by metamatic · · Score: 1

      No, while it may be technically valid, it's no more a good practice than embedding various high-ASCII characters (like #s 179-223) in your filenames. It just makes it extremely difficult for people to retype those things.

      Fortunately I have one of those fancy modern keyboards that has both a tab key and double quotation marks.

      --
      GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
    52. Re:None, I have given up bash scripting by camperdave · · Score: 5, Insightful

      You still need to work with the user's files, which will inevitably have spaces in them. If a space is a valid character in the filesystem then your scripts need to reflect that. Erroring out is not a valid solution.

      --
      When our name is on the back of your car, we're behind you all the way!
    53. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 1, Funny

      No.

    54. Re:None, I have given up bash scripting by elfprince13 · · Score: 1

      Here's what you need to know: put double quotes around things containing whitespace, anywhere it could be an argument to something else, or anything that could contain whitespace if taken as input from a user. It's as simple as that. Really.

    55. Re:None, I have given up bash scripting by Dog-Cow · · Score: 1

      The proper solution is to bash your head in and point to you as example when other programmers write shitty code.

    56. Re:None, I have given up bash scripting by QuantumRiff · · Score: 1

      They could make it object Oriented, and call it PowerShell!
      http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx

      In all seriousness, at work i have to use windows, and I'm starting to move some old VB Scripts others have developed to Powershell for fun, and its nice. Kind of reminds me of Bash and Perl Getting married, and their kid grows up and rebels by moving in with Windows.

      Its not bad.

      --

      What are we going to do tonight Brain?
    57. Re:None, I have given up bash scripting by bipbop · · Score: 1

      I'm stunned that people are defending what is basically incompetence. In Larry Wall's terminology, we're talking about False Laziness--it saves you effort up front, but in the end may cost you more than you've saved.

      Mozilla's build script has this flaw, incidentally:

      Mozilla may not build if some tools are installed at a path that contains spaces or other breaking characters such as pluses, quotation marks, or meta characters. The Visual C++ tools may be installed in a directory which contains spaces (the default install location is preferred).

    58. Re:None, I have given up bash scripting by ari_j · · Score: 1

      The question wasn't about competent programmers. It was about the group consisting of "all the end users out in the world." If your script breaks anytime it is used by someone other than a competent programmer, then the blame for the results rests on your head.

    59. Re:None, I have given up bash scripting by Waffle+Iron · · Score: 1

      That's why you error out when you encounter such a file.

      Annoying developers who "error out" because they can't be bothered to handle an extremely common real-world filename character shouldn't be surprised if they find themselves near the top of the "dead wood" list at the next round of layoffs.

    60. Re:None, I have given up bash scripting by Sir_Lewk · · Score: 1

      That's fine and dandy for regular usage*, but in scripts that are passing around filenames in pipes and whatnot, that is not really a very good solution. You're far better off using find and xargs as the other commenter noted, or finding another way to working completely. Trying to insert '"' chars in the right places in streams will drive you crazy after a while.

      *I use zsh, which handles escaping of space characters for me. Zsh's completion options are really badass.

      --
      "linux is just DOS with a UNIX like syntax" -- Galactic Dominator (944134)
    61. Re:None, I have given up bash scripting by Blakey+Rat · · Score: 3, Insightful

      (try opening a DOS shell on XP and typing in a command using a filename with spaces, without quotes).

      Yah! Now try typing a command without using the letter 'R' or 'C'!!

      Oh wait, you're introducing a ridiculous handicap to demonstrate your retarded point. Turns out, here in the real world, keyboards actually *do* have a key for typing quotes-- so it doesn't fucking matter if the command requires quotes.

      Look, regardless of your "special" way of naming files, the point is that *other people* who don't share your retarded opinion are going to put spaces in the filenames sooner or later-- so you need to be able to cope with it!

    62. Re:None, I have given up bash scripting by Hurricane78 · · Score: 1

      Uuum, it seems you have fallen for the one-language-for-everything fallacy.

      Bash is not made for big scripts. If your script is bigger than one or two screen pages, I recommend moving on to a full scripting language. I prefer Python here.
      And this continues. If your code has more than a hand full of files/modules, I recommend switching to Haskell, C/C++, Java, or something more fitting.

      In my experience, things grow over time, until they fulfill their purpose and any further growth would result in a monolithic block of bloat. Which is the reason most desktop apps are just exactly that, or about to become like that, while shell tools tend to stay smaller. What we need, is to modularize our GUI apps just like we do with the CLI ones.
      There are already ideas that go in that direction. From plug-ins over Firefox extensions to all kinds of applets and plasmids. But they all feel like someone did not entirely think it trough to the end.

      In a sentence: What they lack is a standard interface for combination. Equivalent to the bash pipes and I/O streams.
      In bash, it’s all text (normally). But for efficiency reasons, this should be proper data structures for our modern GUI tools.

      A beautiful example of this is Maya.
      Everything you do in Maya’s GUI, is also a command in its shell (nowadays in Python).
      You can open the console, mark your last actions, and drag them to the button shelf as-is. Done.
      Now you can then edit that code later, to add loops, properties boxes, other GUI elements, variables, etc.

      I really really wish, KDE and Gnome would stop imitating every new horrible function MS thinks up, and start innovating, by doing something like this on the graphical sell level.
      (I was shocked when I looked at Windows 7 and Vista, and found all those new functions I saw in KDE4 and thought would be their innovation, to be actually standard Windows functions. The only difference: They felt a bit more amateurish and were partially missing functions in KDE4. This is the first KDE, where I literally had to use a old technique I thought I buried with my old Windows installation: After a fresh installation, having to go trough all the menus, and simply switch everything to the exact opposite, to get a working system, usable by actual humans with a working brain. It’s so sad. :(( )

      --
      Any sufficiently advanced intelligence is indistinguishable from stupidity.
    63. Re:None, I have given up bash scripting by elfprince13 · · Score: 1

      Maybe I'm getting my experiences with tcsh and bash mixed up, but I spent a summer doing shell scripting on a cluster as a job, and I don't remember having difficulty other than one instance where I was having problems escaping `s in a nested rsh command line.

    64. Re:None, I have given up bash scripting by citab · · Score: 0, Troll

      The real problem is that users insist on having spaces in their damn filenames... I ALWAYS preach against that to users... It's bad practice to have spaces in directory (folder names for stinking windoze users) or filenames in the first place.

      Users who insist on it should be flogged severely! (with old floppy disks)

      BOFH

    65. Re:None, I have given up bash scripting by Sir_Lewk · · Score: 1

      I've run into issues with generating lists of files, grepping through them, and preforming tasks like writing them to a file in a certain format or whatnot. Generally any problems I've encountered have been solved by just reworking my solution to be more "correct", so it might be fair to say that you only really run into issues if you're lazy the first time around (which would explain my past issues ;).

      --
      "linux is just DOS with a UNIX like syntax" -- Galactic Dominator (944134)
    66. Re:None, I have given up bash scripting by daveX99 · · Score: 1

      ... The syntax and semantic are simply to wierd... I am a fulltime linux used...but I newer script it

      Yikes: I'm not a Grammar Nazi, but your post is full of typos. Could that be your problem with the shell's syntax?

      And it can't handle filenames with space in them without some serious hack magic.

      ?? do you mean a '\ ' ? Again, I say, "yikes".

    67. Re:None, I have given up bash scripting by vgaphil · · Score: 2, Informative

      You can manipulate the IFS variable if you are having problems with files with spaces.

      IFS=$'\n'

      for i in $(find /some/dir -type f)
      do
      echo $i
      done

      unset IFS

      --
      A clever person solves a problem. A wise person avoids it. -- Einstein
    68. Re:None, I have given up bash scripting by adonoman · · Score: 1

      And then you could add in some a GUI platform to let you present information in graphical windows say, and call it Windows Presentation Foundation.

    69. Re:None, I have given up bash scripting by TheSunborn · · Score: 1

      [quote]
      About spaces:

      ?? do you mean a '\ ' ? Again, I say, "yikes".
      [/quote]

      No ofcause not. I mean things such as

      xmms `locate Techno`

      not working with names containing spaces. But this thread have produced some interesting work arounds for that.

      And there is a similary problem if you use for/forall to loop over all the files in a directory.

    70. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Under what circumstances do filenames have spaces in them. Space is a delimiter and so won't be in a filename. Fix the problem at source, or suffer forever.

    71. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      spaces were never allowed as file names, nor were they common practice until some idiot thought it'd be *keen* to allow it.

      no - just would prefer they never *started* using spaces.

      in grammar, word processing, data - they make sense.
      in file or path names, no - they don't make sense, never have, never will - spaces have been, and should remain, delimiters in the filename arena.

    72. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      It's
      Hacker!\ Hacker!

    73. Re:None, I have given up bash scripting by Grishnakh · · Score: 1

      Fortunately, as an embedded Linux driver developer, writing bash scripts isn't part of my job description. I do write bash scripts, but they're for my own personal use to make my work easier, not for others' use, and I don't make files with spaces in their names.

    74. Re:None, I have given up bash scripting by Grishnakh · · Score: 1

      Again, how many "regular users" run bash scripts, or even know how to use the bash shell?

      To me, a bash script is something I write to automate my own work, or perhaps to share with my workgroup (who are all similar to me in ability). It's not something that I'd expect to have any serious error-checking, or to be used by any non-programmers. If you're writing something like that, 1) it's probably going to have a GUI, and 2) it's very unlikely to be a bash script.

    75. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      It\'s

      Hacker\!\ Hacker\!

    76. Re:None, I have given up bash scripting by iluvcapra · · Score: 1

      Is this seriously an argument? xargs has -0, use it. Computers work for us and should conform to our cultural and linguistic norms, and we shouldn't start moralizing about the fact that somebody forty years ago loaded ASCII(20) with particular meaning.

      --
      Don't blame me, I voted for Baltar.
    77. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 1, Interesting

      That was "Program Files", or "PROGRAM~1", as it was known to the typical Windows 95 era installer script.

    78. Re:None, I have given up bash scripting by ari_j · · Score: 1

      Just so I'm clear on this, you believe that only programs with GUIs should be robust in checking for malformed input? (Which, for you, appears to include filenames with spaces in them.)

      Also, you misquoted me and the parent again. It's not about "regular users." It's about "all the end users out in the world." That includes other programmers who are competent but do not share your assumptions about filename constraints, which are of course not based on any filesystem constraints but rather simply on your own preconceived notions.

      It also includes people whose systems run the script for them, as is the case with /etc/init.d scripts and the like. Your position appears to be that competent programmers should allow their scripts to destroy users' data whenever the users have filenames containing spaces.

      If you do release a script to the public for any reason, please sign it with your Slashdot ID so we can all sift through it for similar assumptions before running it and corrupting our data. Heaven knows what other idiosyncratic constraints you believe the world should follow.

    79. Re:None, I have given up bash scripting by DaleGlass · · Score: 1

      That has nothing to do with bash.

      Tar outputs data, xargs reads that data as-is without the shell's intervention. It will work the same whether you use bash, zsh, or anything else. The issue is only due to how that data is formatted on the output and interpreted on the input.

      In this case tar appears to be missing an option that would write a \0 after each filename, which seems a bit odd for a GNU utility. Especially since it can read lists terminated in such a way.

      Nothing a patch wouldn't fix though.

    80. Re:None, I have given up bash scripting by pclminion · · Score: 1

      xargs? Eww.

      for F in `tar tf file.tar`; do rm "$F"; done

    81. Re:None, I have given up bash scripting by inKubus · · Score: 1

      Ugh, the worst I encountered recently where I needed to run sed over an ssh connection from the script. So there's the usual multiple levels of quotes and escaping. I'm still not fully up to speed on what order it does the quotes, especially with sed involved, so I just scp the script to the host and run it remotely then delete it. Not the best but what can you do. I guess I could redirect the script into the ssh... oh well, what's done is done.

      --
      Cool! Amazing Toys.
    82. Re:None, I have given up bash scripting by ClosedSource · · Score: 1

      It's not a limitation, it's a bad practice trap!

    83. Re:None, I have given up bash scripting by Lorens · · Score: 1

      I just scp the script to the host and run it remotely then delete it. Not the best but what can you do. I guess I could redirect the script into the ssh

      People often forget that ssh not only lets you specify a command to run with its arguments, but also redirects stdin and stdout.

      So

      scp list host:
      scp script host:
      ssh host 'command result'
      scp host:result result
      ssh host rm script list result

      can be advantageously replaced by

      ssh host command result

      I suppose you could pipe your script to sh, but I prefer having all my scripts on all my servers and updating them when necessary.

    84. Re:None, I have given up bash scripting by ae1294 · · Score: 1

      Doggone it! You'd think, after 25 years of Unix, I'd know about that option. That's a good one. Thanks.

      Well to be fair the source patch was just released for testing a few days ago. ;-) So feel free to update those man pages!

      HONESTLY WON'T SOMEONE THINK OF THE MAN PAGES!!!!

    85. Re:None, I have given up bash scripting by Lorens · · Score: 1

      I actually proofread the text during preview but not the "ssh host command lessthan list greaterthan result". Plain Old Text? No way.

    86. Re:None, I have given up bash scripting by Lorens · · Score: 1

      Spaces are a pain, but having witnessed how broken some OSes are when it comes to handling anything beyond the most basic, the advice I give is deviate from the extremely basic at your own risk.

      It's called "Be liberal in what you accept, and conservative in what you [provide]". STD 5/RFC 791.

      I remember a while back trying to put my MP3s in a NTFS disk and having to deal with the several ? that the program had put into some filenames. The OS I did that on was fine with it, but when I got to Windows it was impossible to delete or really work with.

      Oh, the joys of non-ASCII characters in filenames! UTF8, ISO8859-x, whatever is used on Windows . . . The problem is that for *ix, no characters are illegal except NUL and forward slash. Reading a windows disk can be a real pain, but when I had to do that conversion last time, I found a script to do it in about five minutes of googling.

    87. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      So why the hell have you been claiming you have a solution for this problem, when your solution is "I let no-one else use this scripts and even I only use these scripts on files I have produced myself?

      You must have understood most other people are not in that situation.

    88. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Spaces in filenames started with Microsoft. I'll say no more.

    89. Re:None, I have given up bash scripting by PAjamian · · Score: 1

      tar tf file.tar | xargs -d '\n' rm

      --
      Windows is a bonfire, Linux is the sun. Linux only looks smaller if you lack perspective.
    90. Re:None, I have given up bash scripting by PAjamian · · Score: 1

      Simple solution: don't use filenames with spaces in them. They're an incredibly stupid idea. If you need something that looks like a space, use an underscore.

      That's easy enough to say until you get a zip file from your relatives with all the pics from their vacation complete with lots of descriptive filenames with spaces in them. You don't always have control over the names of your files and it's often times a lot easier to just learn to deal with filenames with spaces in them than to go and rename a large batch of files that you get.

      --
      Windows is a bonfire, Linux is the sun. Linux only looks smaller if you lack perspective.
    91. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      There are filesystems that allow newlines in filenames?

    92. Re:None, I have given up bash scripting by flajann · · Score: 1

      You might just consider doing a filename scrub -- renaming the files to something more script-friendly during processing. Or you can create soft links to the filenames riddled with spaces before processing, and just delete the links when you're done. There's a number of ways to skin the "space in the filename" cat issue.

    93. Re:None, I have given up bash scripting by flajann · · Score: 1
      I would prefer using Ruby instead of Perl in that regard -- except, of course, you have the issue of whether or not Ruby is installed, and what version of Ruby is there. Ran into that headache big time with RedHat distros -- they were always 2 or 3 revisions behind what was GA.

      Perl definitely has its place, though!

    94. Re:None, I have given up bash scripting by seebs · · Score: 1

      Quotes aren't nearly enough to deal with filenames with spaces in them in the general case. Try xargs... You need the "-0" option, which isn't all that portable, to handle names with spaces in them. (Or backslash escapes, but you can't do those for newlines in the general case because you can't tell whether a newline is a legitimate new entry or part of a file's name...)

      That said, rc and es are both good examples of languages recognizably related to the shell (and in particular, where the primitives are "any command you want", rather than the subset built into the language or loaded as libraries), but which have the quoting stuff better.

      --
      My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
    95. Re:None, I have given up bash scripting by daffmeister · · Score: 1

      To me, a bash script is something I write to automate my own work, or perhaps to share with my workgroup (who are all similar to me in ability).

      Good for you, but that's a pretty limited set of the areas where bash scripts are used.

      Scripts are commonly used to automate tasks that have to run on files from all sorts of places. Many of those files will have spaces. The script failing to run is not an option.

    96. Re:None, I have given up bash scripting by vrt3 · · Score: 1

      Filenames with spaces in them are not broken; code that fails to deal with them is broken.

      There are no good reasons not to use spaces in filenames, other than code that doesn't handle it because of wrong assumptions. That is a failure of the code, not of the user wanting to use meaningful filenames. The OS exists to give the user a nice interface, within reasonable limits; not to impose arbitrary limits.

      It's true that Unix command line and script environment doesn't handle spaces very well. I think that's sad.

      --
      This sig under construction. Please check back later.
    97. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Well, try saying that in (pick your vendor) GUI!

      And since xargs has it's problems I'm usually writing like this:

      find -type f -iname '*hello world*" | while read f ; do rm "$f" ; done

      For shell scripts little different syntax isn't a big deal.

      Bash may slower than (put your language here). But who really cares if you're using only for trivial things. Nobody told you to try video encoding with bash scripts :)

    98. Re:None, I have given up bash scripting by HyperQuantum · · Score: 1

      Does `find . -print0 | xargs -0` really qualify as "serious hack magic"?

      IMHO there should have been a bit more restrictions on what characters a Unix filename can contain. It would make (scripting) life a lot easier. For example: why did they allow newline characters?

      And there are other problems as well. Check this out:

      Why does the wc utility generate multiple lines with “total”?

      --
      I am not really here right now.
    99. Re:None, I have given up bash scripting by halfnerd · · Score: 1

      IIRC POSIX allows any characters (bytes) except '/' and '\0' in filenames.

    100. Re:None, I have given up bash scripting by HyperQuantum · · Score: 1

      Simple solution: don't use filenames with spaces in them. They're an incredibly stupid idea.

      Another simple solution: stop using spaces as argument delimiters in the commandline. That's outdated.

      Seriously, the best way would be to have a character that cannot be used in filenames and that is easily available for use in a commandline (can be typed without compose key).

      --
      I am not really here right now.
    101. Re:None, I have given up bash scripting by psmears · · Score: 1

      xargs? Eww.

      for F in `tar tf file.tar`; do rm "$F"; done

      But that still fails when the filenames contain spaces:

      bash$ touch "filename with spaces"
      bash$ tar cf file.tar "filename with spaces"
      bash$ for F in `tar tf file.tar`; do rm "$F"; done
      rm: cannot remove `filename': No such file or directory
      rm: cannot remove `with': No such file or directory
      rm: cannot remove `spaces': No such file or directory
      bash$

    102. Re:None, I have given up bash scripting by cpghost · · Score: 1

      My vote is for perl. It's more common in a "base install" than any other shell (in the BSDs and most Linux distros) and has a non-trivial amount of power.

      Perl isn't part of the base install in FreeBSD, and Python is necessary in Gentoo. IMHO, availability in the base install shouldn't be a criterion for or against a language, because that can be easily remedied by the distromakers.

      --
      cpghost at Cordula's Web.
    103. Re:None, I have given up bash scripting by Taladan · · Score: 1

      If spaces are a problem, use tr to translate them to underscores during the script to deal with them. Is the spacebar really worth three hours of flame? Seriously: man tr

      --
      I can't believe what a bunch of nerds we are. We're looking up "money laundering" in the dictionary.
    104. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      No, while it may be technically valid, it's no more a good practice than embedding various high-ASCII characters (like #s 179-223) in your filenames. It just makes it extremely difficult for people to retype those things.

      By high-ASCII, I assume you mean non US-ASCII glyphs (most file systems and operating systems support unicode these days, even Windows have some support for Unicode, even if it is slightly broken).

      If all users of a system use the same non-US keyboard it is extremely simple for people to retype "those things". Limiting file names to only English or only English characters makes no sense at all. It is as senseless as limiting yourself to only four all-cap characters in filenames and only one level of directories. Don't complicate everything by preventing problems that don't exist or are extremely rare.

      But I do hate applications that use key combinations with <>{}[]?~^'()$|\ et.c. as the default keyboard shortcuts, because most of those are not possible to use on most of my computers (some of my laptop keyboards don't even support ctr++ and ctrl+-).

    105. Re:None, I have given up bash scripting by digitalsushi · · Score: 1

      Dealing with in bash is definitely one of the things that makes it pretty gross.

      A space is the default field separator. You can change this by setting the IFS variable. Let's say you want to manipulate a directory of mp3 files with spaces in the name:

      IFS=$'\n' && for each in *;do convert $each;done

      Yay, it tokenizes on file names instead of words in the file, and it does what you meant.

      --
      slashdot: where everyone yells sarcastic metaphors to themselves to understand the issue
    106. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Computers work for us and should conform to our cultural and linguistic norms

      My name is Con Aux, you insensitive clod!

    107. Re:None, I have given up bash scripting by lytithwyn · · Score: 1

      I realize perl can often (usually) be difficult to read

      You know, I can't seem to get over this part. You're right on target when you say it's more common in a "base install", but I just can't get past how hard it is for me to read. I don't know, maybe I'm weird, but I gave up trying to use the stuff. I have been known to use php in cli mode instead, even though it may not be as ubiquitous as perl. I just started looking at Ruby, and so far I like it pretty good too.

      Either way, when I see perl code I can't help but think about something a friend of mine told me once...he said perl code looked like he puked ASCII chunks in his terminal.

    108. Re:None, I have given up bash scripting by tepples · · Score: 1

      There is absolutely no good reason to have a space in a filename.

      Tell that to anybody who names files like thank you letter to Kathy.odt

    109. Re:None, I have given up bash scripting by just_another_sean · · Score: 1

      It's true that Unix command line and script environment doesn't handle spaces very well. I think that's sad.

      The shell handles spaces just fine. Quoting and escaping offer several ways to handle spaces depending on context. It's people
      that don't understand the shell that don't handle spaces well (like the OP).

      --
      Creationist Textbook Stickers Declared Unconstitutional by CowboyNeal
    110. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Spaces are delimiters. They are visual clues to separate written and spoken language. Shell people use them to separate commands. No surprise there. Users use spaces to delimit words. Asking users to use hypens or underscores is reasonable. The fact that most OSs tolerate spaces gridgingly (did any one say %20?) we geeks of the world should unite and guide users away from using the space as an integral part of a file name. Ne edI sayan ymore? Using a hack to allow users to embed spaces seems unwise. "abc%20def" != "abc def".

    111. Re:None, I have given up bash scripting by rubycodez · · Score: 1

      Let's be professional, the officially recognized description by the IT industry of how Perl looks is "whale guts".

    112. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Set IFS=$'\n' before processing files with spaces. It will save you a ton of time.

    113. Re:None, I have given up bash scripting by Just+Some+Guy · · Score: 2, Informative

      Use:

      tar -t --null -f file.tar | xargs -0 rm

      That will work unless the filenames contain nulls in them. They won't.

      --
      Dewey, what part of this looks like authorities should be involved?
    114. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      Simple solution: don't use filenames with spaces in them. They're an incredibly stupid idea.

      Simple solution: learn to quote and escape your strings properly.

    115. Re:None, I have given up bash scripting by Richy_T · · Score: 1

      Spaces are allowed characters in filenames and so should be expected. It is up to the script to be able to handle it. It's been a nasty kludge to avoid spaces and has led to lack of general education on the issue, development of better solutions and many many broken scripts.

      That said, "c:\Documents and Settings" is just stupid.

    116. Re:None, I have given up bash scripting by Richy_T · · Score: 1

      Should be "failure to develop better solutions"

    117. Re:None, I have given up bash scripting by Richy_T · · Score: 1

      Thankfully, we only get "thank you letter to Kathy.ppt" round these parts.

    118. Re:None, I have given up bash scripting by johnshirley · · Score: 1

      Hack magic? They're called quotes. If a string has spaces in it, I enclose the entire string in quotes. One could also delimit the spaces with a backslash in a one-liner. Sometimes, I change the Input Field Separator (IFS) to exclude spaces within a script. It's not magic. Just the nature of language.

    119. Re:None, I have given up bash scripting by Richy_T · · Score: 3, Insightful

      It doesn't have to be that way. I always try and write Perl to be readable rather than concise. Sure I might take 6 lines to do something that can be done in 1 and may use some other stuff that isn't particularly necessary but I'm writing to get the job done and for maintenance, not to show how clever I am.

    120. Re:None, I have given up bash scripting by Richy_T · · Score: 1

      Powershell is interesting. I have dipped my toes in a little but there are several places which really make my head hurt but a few features that would be nice to see in a Unix scripting language. I think it has an interesting future ahead of it.

    121. Re:None, I have given up bash scripting by Blakey+Rat · · Score: 1

      The fact that most OSs tolerate spaces gridgingly (did any one say %20?) we geeks of the world should unite and guide users away from using the space as an integral part of a file name.

      No, "we" (and by which I mean "you", since I already actually care about usability) should bend computers to meet human behavior, not to futilely attempt to get humans to emulate computer behavior. Especially since the latter course will inevitably fail.

      If computer don't take into account that users like to separate words with spaces, then the computer is the flawed party, not the user. And if you're defending the computer, and thus making life harder for users, you're a gigantic asshat.

    122. Re:None, I have given up bash scripting by cyberthanasis12 · · Score: 1

      Seriously now. You expect all the end users out in the world to stop using spaces... just so your script works?

      Seriously now. You expect all the end users out in the world to stop using GOTO... just because your favorite language (PYTHON) lacks this wonderful, absolutely necessary, versatile command?

    123. Re:None, I have given up bash scripting by spongman · · Score: 1

      "c:\Documents and Settings" is just stupid

      of course, you should never directly refer to that directory, making its stupidity irrelevant.

      you should always call SHGetKnownFolderPath to refer to special locations.

    124. Re:None, I have given up bash scripting by vux984 · · Score: 1

      You expect all the end users out in the world to stop using GOTO

      How many end users use GOTO?

      just because your favorite language (PYTHON) lacks this wonderful, absolutely necessary, versatile command?

      I'm not actually a fan of Python. I think using whitespace for semantics (e.g. block delineation) is demented.

    125. Re:None, I have given up bash scripting by pclminion · · Score: 1

      WTF? I've done this before. Why are the double quotes not quoting the $F?

    126. Re:None, I have given up bash scripting by Darinbob · · Score: 1

      Of course, carriage returns are allowed in file names too on some systems.

    127. Re:None, I have given up bash scripting by DaleGlass · · Score: 1

      The only problem with that is that it doesn't work. I did RTFM before posting, and also actually tried it out.

      Run "tar -t --null" through hexdump -C, you'll see there are no 00s in there, and it's all 0a, or newlines.

      For some reason --null only applies to reading file lists, and not to producing them, at least as of tar version 1.22.

    128. Re:None, I have given up bash scripting by Richy_T · · Score: 1

      Not easy to do at a dos prompt or in a .bat file

    129. Re:None, I have given up bash scripting by k1773re7f · · Score: 1

      Or even other perl people for that matter. I have gone back to perl scripts I myself wrote a couple years back, being in too big a hurry to document them along they way and finding myself saying, WTF?
      python? Dang man! I am still looking for the line that isn't idented just right.
      I always go back to awk or tcl/tk for texty gui thingies and bash or ksh for systemy thingies.

      --
      This sig. intentionally left blank.
    130. Re:None, I have given up bash scripting by cayenne8 · · Score: 1
      "Unless your filenames contain spaces, then you should know what $IFS does."

      What does it do?

      --
      Light travels faster than sound. This is why some people appear bright until you hear them speak.........
    131. Re:None, I have given up bash scripting by Anonymous Coward · · Score: 0

      I've found GNU xargs's -i to be generally more useful than delimiter magic:

      tar tf file.tar | xargs -i THIS rm "THIS"

      (use -I on OSX and maybe other BSD-alikes)

    132. Re:None, I have given up bash scripting by lewiscr · · Score: 1

      Perl is just as easy to read as all the other C derivatives. Like the parent says, if you want readable Perl code, write it that way.

    133. Re:None, I have given up bash scripting by ToasterMonkey · · Score: 1

      Most of these issues were resolves years (or decades) ago; it's only now with Windows and developers coming from the broken Windows platform that these issues are coming up again.

      The only reason you're having "so many issues" is because you're trying to apply a Windows mindset to Unix, as seen in your comment about spaces in filenames. All the stuff in Unix (and now Linux) has been built up over 40 years of use and development.

      The problems of using spaces in filenames were resolved by unanimous consent not to use them? Really?

      7-bit ACSII is probably good enough for everyone too, huh? I18n _solved_, on Slashdot - you saw it here first folks.

    134. Re:None, I have given up bash scripting by lytithwyn · · Score: 1

      Ha ha....I can definitely see the resemblance!

    135. Re:None, I have given up bash scripting by Qzukk · · Score: 1


      WTF? I've done this before. Why are the double quotes not quoting the $F?

      It's already split up by the "for ... in ..." construct based on the characters set by $IFS (space, tab, newline by default).

      --
      If I have been able to see further than others, it is because I bought a pair of binoculars.
  6. Gtk2-Perl by vandan · · Score: 1

    I really can't praise Gtk2-Perl enough. Using Glade to quickly build your GUI, and Perl to quickly build your logic, it's a knock-out combination. The end result looks just like a gnome application ( using Gtk2 ), and for 95% of cases, runs as fast as well. I liked it so much, I wrote some database classes, Gtk2::Ex::DBI and Gtk2::Ex::Datasheet::DBI ... see: http://entropy.homelinux.org/axis/.

    1. Re:Gtk2-Perl by grcumb · · Score: 1

      I really can't praise Gtk2-Perl enough. Using Glade to quickly build your GUI, and Perl to quickly build your logic, it's a knock-out combination.

      Heh, I'll see your GUI and raise you transparency. I've got a little dashboard applet that uses X11::Aosd to display a translucent status display for all my key servers. Yes, I know I just re-invented Conky, but because it's Perl I can use SSH::RPC in the back end to securely talk to my servers in order to get quick and dirty performance metrics.

      One of the things scripting does well is to chop tasks into small, manageable steps. While system monitoring is a complex and demanding process, all I really need on my desktop is something about as sophisticated as a baby monitor. In the first instance, I don't need to know what's wrong; I just need to know that something's wrong.

      Screenshot here, if you're into that kind of thing. It's simple and slightly boring, really, but that's by design. It's not supposed to sing and dance, and above all, it's not supposed to cry wolf. It's just supposed to sit there quietly and let me know that my servers are healthy and happily chugging along.

      --
      Crumb's Corollary: Never bring a knife to a bun fight.
  7. It's pricey but.... by Fluffeh · · Score: 2, Funny

    I always request the budget for a small unit of scantily clad maidens from management in addition to the team beer budget.

    One day.... one day....

    --
    Moved to http://soylentnews.org/. You are invited to join us too!
    1. Re:It's pricey but.... by styrotech · · Score: 1

      You have scantily clad maidens as management?

      Whether that would be a good thing or a bad thing depends on the maidens I suppose.

    2. Re:It's pricey but.... by Anonymous Coward · · Score: 0

      Are there maidens in management? I thought management had already lost all innocence.

  8. Zenity by Anonymous Coward · · Score: 0

    Zenity: http://live.gnome.org/Zenity
    So easy, my grandma could use it.

  9. I've been having better luck with applescript by jordan314 · · Score: 1

    In OS X, for simple user interaction I've been having better luck with applescript. It's easy enough to alert and get user input with the "display dialog" command, and then I can run "do shell script" to execute my scripts. I can save them as application bundles, I can give them custom icons, they appear in the dock when running, or I can optionally hide them from the dock with LSUIElement. The ability to run interapplication commands and the UIElementInspector tool is a boon for being able to perform powerful multi-app interactions.

    1. Re:I've been having better luck with applescript by FictionPimp · · Score: 1

      You can also call GUIs made with interface builder with AppleScript.

  10. Easy ways of GUI scripting by houghi · · Score: 1

    "Developing GUI script-based applications is time-consuming and expensive"

    KDialog and Zenity are pretty easy to write a script that can be used in a GUI. The underlying thing is just bash (or whatever) itself.

    --
    Don't fight for your country, if your country does not fight for you.
  11. Off the top of my head... by hkz · · Score: 4, Informative

    I work as a Linux netadmin and system developer, so I do a lot of shell programming in (ba)sh. Here's some of the niftier things you can do to a shell script:

    - Make colored output with shell escape sequences. Works especially well with red type for error messages, makes them really stand out.
    - Use inline functions a lot. The great thing about them is that you can pipe to them and use them in all kinds of places. For instance, to do mysql queries:

    mysql_query() { /usr/bin/mysql --user=root --pass=topsecret database
    }

    echo 'SELECT * FROM accounts' | mysql_query

    - "Here documents". For long MySQL sequences, something like the following (reusing the mysql_query function from above):

    cat - EOF | mysql_query
          SELECT bar
          FROM foo
          WHERE baz ...
    EOF

    This lets you easily format stdin for scripts and other programs. Also really useful for outputting HTML and stuff like that. Best thing is that variables are expanded inside the block.

    - The || and && operators. Check if a file exists, remove if so, else complain:
    [ -f /tmp/somefile.txt ] && rm /tmp/somefile.txt || echo "Does not exist!"

    Also common in this form:
    [ -x /usr/bin/necessaryprogram ] || { echo "aaargh"; exit 1; }

    - Making a "multithreaded" shellscript is also one of my favourites. Say, you want to start five virtual machines at the same time. Write a function that starts a vm, and call it a few times in a loop, backgrounding each instance with &, and saving their PIDs. Then have a "wait loop" that waits for the PIDs to exit the system (or for a timeout to occur).

    - Proper argument handling with getopt. Have your script take "real" arguments in any order, just like real binaries.

    This just scrapes the surface of the surface, of course. I learn new stuff every day.

    1. Re:Off the top of my head... by Anonymous Coward · · Score: 0

      The general concept of using functions is good, but you might want to look into the "-e" option for mysql.

    2. Re:Off the top of my head... by buchner.johannes · · Score: 1

      Just as a few examples: These don't work as you think they would.

      for f in a b c; do
          [ -x "$f" ] || { echo "file $f exists" && continue }
          [ -x "$f" ] || echo "file $f exists" && continue
      done

      At some point you need deeper understanding than bash can provide data structures, error handling etc. Then you need python or java or something.

      --
      NB: The message above might reflect my opinion right now, but not necessarily tomorrow or next year.
    3. Re:Off the top of my head... by shallot · · Score: 1

      For instance, to do mysql queries:

      mysql_query() { /usr/bin/mysql --user=root --pass=topsecret database }

      echo 'SELECT * FROM accounts' | mysql_query

      Umm, I'm sure I'm not the only one to notice, but it looks like I'm the first to tell you that you have a grave security bug in that code - while you are executing any such script, other users on the same system who know how to use ps(1) can see your MySQL root password.

      Read the fine manual mysql(1) and look up --defaults-extra-file.

    4. Re:Off the top of my head... by Per+Wigren · · Score: 1

      Here are some of my "tricks" I use regularly.

      Diff the content of two tar.gz files:
      diff <(tar tvfz foo.tar.gz | sort) <(tar tvfz bar.tar.gz | sort)

      The <(some command) trick works with all commands that takes a filename as parameter and is a good alternative to using temporary files.

      Fork off five subcommands that sleeps for 0-15 seconds and wait until all of them are finished:
      while test $(( foo++ )) -lt 5; do
      ( sleep $(( $RANDOM & 0xF )); echo "Hello from $foo" ) &
      done
      echo "Waiting..."
      wait
      echo "All done."

      Set a variable to a default value if it's not already set:
      % echo $X

      % echo ${X:-42}
      42
      % echo $X
      42
      % X=50
      % echo ${X:-42}
      50

      If using temporary files, use mktemp and the files will always be deleted when the script exits:
      TMPFILE=$(mktemp)

      Run other cleanup code on exit, even if the script was interrupted:
      trap "psql -c 'drop table my_temp_table'" EXIT

      Append ALL stdout and stderr output from the rest of the script to a file:
      exec 2>&1 >>/var/log/myscript.log

      That's just the top of my head. I can REALLY recommend reading the free Advanced Bash-Scripting Guide (more formats) from cover to cover! Every time I skim it I find something new that I missed before.

      --
      My other account has a 3-digit UID.
    5. Re:Off the top of my head... by l0b0 · · Score: 1

      Make colored output with shell escape sequences. Works especially well with red type for error messages, makes them really stand out.

      Sounds like you really know your stuff, so I hope you can answer these:

      • How do you detect whether the shell supports color?
      • What does the output look like if the shell doesn't support color (I don't think I've ever used one) and you try to output colored text?
      • Examples?
    6. Re:Off the top of my head... by hkz · · Score: 1

      MySQL replaces the password in the process table with a series of 'x' characters. Try it. The password is safe. While I agree that not passing anything on the commandline is a better solution, my MySQL version (5.0.67) does not support --defaults-file or --defaults-extra-file.

    7. Re:Off the top of my head... by theCoder · · Score: 1

      You mean because -x tests to see if the file is executable, not if it exists? Or the fact that you're saying the file exists if it is NOT executable?

      The easiest way to execute multiple statements if an expression is true is to do something like:

          if [ -f "$f" ]; then echo "file $f exists"; continue; fi

      It is true that more complicated tasks often require more complicated tools. But for relatively simple tasks, shell scripts are great!

      --
      "Save the whales, feed the hungry, free the mallocs" -- author unknown
    8. Re:Off the top of my head... by theCoder · · Score: 1

      Diff the content of two tar.gz files:
      diff <(tar tvfz foo.tar.gz | sort) <(tar tvfz bar.tar.gz | sort)

      Wow! I learned something new and useful on /. today! I had never seen the <() syntax, but I can appreciate how useful it can be, especially for tools like diff that tend to take files. For those wanting to learn more, this is called Process Substitution.

      Thanks for this great tip!

      --
      "Save the whales, feed the hungry, free the mallocs" -- author unknown
    9. Re:Off the top of my head... by hkz · · Score: 1

      You can check whether you're outputting to a terminal with test -t. If the output is not going to a terminal (say, to a pipe), you can print a plain vanilla string. You can output colour codes as straight ANSI escapes, or (probably better), use tput.

      Example log function:


      log() {
          test -t 1 && { tput setf 4; cat; tput setf 7; } || cat
      }

      dmesg | log

      This tests whether stdout is a terminal, and if so, prints the text in red. Otherwise (if stderr is redirected to a pipe or file) it prints the plain string.

    10. Re:Off the top of my head... by Anonymous Coward · · Score: 0

      >Write a function that starts a vm, and call it a few times in a loop, backgrounding each instance with &, and saving their PIDs. Then have a "wait loop" that waits for the PIDs to exit the system (or for a timeout to occur).

      Even easier: use the "wait" command. It blocks until all backgrounded processes are done.

    11. Re:Off the top of my head... by wdef · · Score: 1

      I've used all those or similar. Bash's getopt however needs some real improving last time I looked. It's possible to workaround some of its shortcomings but it's somewhat trial and error and I'm not sure how portable workarounds would be. The bored may see my attempts to get getopt to be more useful in [shameless plug] http://tripl.sourceforge.net/ [/end plug]

  12. Since I live in my parent's basement... by the_humeister · · Score: 2, Funny

    I use the usual: sed, [, wget, etc to automate downloads of pr0n.

    1. Re:Since I live in my parent's basement... by Anonymous Coward · · Score: 0

      If people would just use the damn video tag, I wouldn't have to use sed, ftp, and ksh to get my porn.
      Die Adobe, die! (Don't worry, it means "The Adobe, the" in German)

    2. Re:Since I live in my parent's basement... by Anonymous Coward · · Score: 0

      Ahhh, you are lucky to live with your parents. They probably have a pr0nograph. Go upstairs after dark and they are asleep. YourTube just got bigger...

    3. Re:Since I live in my parent's basement... by Ciaran+Power · · Score: 1

      natch. And for and seq.

  13. You mean that VI by garyisabusyguy · · Score: 1

    is not a GUI?

    --
    Wherever You Go, There You Are
    1. Re:You mean that VI by Sir_Lewk · · Score: 1

      More of a TUI if you want to be pedantic.

      --
      "linux is just DOS with a UNIX like syntax" -- Galactic Dominator (944134)
    2. Re:You mean that VI by Anonymous Coward · · Score: 0

      Of course not, it's a VUI. That's why the VISUAL env. variable points to your editor.

  14. I dissent by ZeBam.com · · Score: 2, Insightful

    I disagree with the premise that GUI interfaces are needed, desirable, or constitute "spicing up." Command line scripts are fine and dandy in my book.

    1. Re:I dissent by Dadoo · · Score: 1

      Command line scripts are fine and dandy in my book

      I'm inclined to agree, given that I've written several dynamic web pages in shell.

      --
      Sit, Ubuntu, sit. Good dog.
    2. Re:I dissent by martin-boundary · · Score: 3, Insightful
      It's also plain short-sighted to program a script for a GUI.

      It implies that the script will only be run by human users (and probably, human users who happen to run a particular flavour of GUI). Traditional shell scripts are written for all users, not just human users.

      Why should developers care about non-human users? It's what makes automation possible. Every time time a script delegates work to another script, that's a non-human user scenario.

      If you build enough scripts that can be used by all users, then you have a critical mass and your system becomes really powerful. If you build enough scripts that can only be used by human users, then your system stays weak, for it is limited by the actions of a single human operator.

    3. Re:I dissent by ZeBam.com · · Score: 1

      Excellent points. That's part of the fundamental purpose of unix.

    4. Re:I dissent by Anonymous Coward · · Score: 0

      On the other side of things, I found this article very useful for a desktop guy like myself who wants to integrate custom scripts in the desktop environment. I think of this akin to gnome scripts or something like that.

    5. Re:I dissent by styrotech · · Score: 1

      Why is automation vs UI an either/or question?

      Couldn't a script just use stdin and/or arguments for input and only if nothing was supplied then pop up a GUI or interactively ask questions in the terminal?

    6. Re:I dissent by paimin · · Score: 1

      Or, non-human users can learn how to use a GUI already.

      --
      Facebook is the new AOL
    7. Re:I dissent by Taladan · · Score: 1

      I disagree...when we start writing scripts for non-human users, skynet will be able to find Sarah Conner that much more easily. Screw those non-human users! ;)

      --
      I can't believe what a bunch of nerds we are. We're looking up "money laundering" in the dictionary.
  15. Stop using the Shell by Bruce+Perens · · Score: 4, Interesting

    The shell is a poor clone of 1950's algol. Today, scripting in Ruby or Python yields scripts that can handle errors with advanced facilities like exceptions, and is more maintainable, and can connect to a number of different GUIs or the web.

    1. Re:Stop using the Shell by sribe · · Score: 1

      The shell is a poor clone of 1950's algol. Today, scripting in Ruby or Python...

      It was a great day when I decided no more bash scripts, ever. Ruby is so much nicer...

    2. Re:Stop using the Shell by ZeBam.com · · Score: 1

      Perl!

    3. Re:Stop using the Shell by walkoff · · Score: 2, Interesting

      There are times when bash/ash/dash... are all that is available or can be made available. Ruby and Python and the myriad other scripting languages are all very good but in memory, cpu and diskspace starved devices shell is the way to go. even the mini-versions of perl and Ruby etc. are a PITA to get working in embedded devices especially if you are using uClibc.

    4. Re:Stop using the Shell by Bruce+Perens · · Score: 3, Interesting

      I like Larry and the rest of the crew, but I think we can confidently say that Ruby is an evolution from Perl. It used to be that CPAN was a big advantage, but ruby gems have come along pretty well since then. And there's a lot to be said for the Rails framework, even more in 3.0 .

    5. Re:Stop using the Shell by Bruce+Perens · · Score: 4, Interesting

      There are times when bash/ash/dash... are all that is available or can be made available

      Because you're running Busybox. Which means it's my fault :-)

      The evolutionary successor of busybox, which I've been thinking about for a while, will not use the shell language. We can raise the bar significantly.

    6. Re:Stop using the Shell by bcrowell · · Score: 1

      I like Larry and the rest of the crew, but I think we can confidently say that Ruby is an evolution from Perl. It used to be that CPAN was a big advantage, but ruby gems have come along pretty well since then. And there's a lot to be said for the Rails framework, even more in 3.0 .

      My experience is that the quality of ruby's implementation has a long way to go before it's comparable to perl's. Here is a bug report I filed back in 2007 -- still open, three years later. I've never experienced bugs like this in perl.

    7. Re:Stop using the Shell by vtcodger · · Score: 1, Informative

      ***The shell is a poor clone of 1950's algol.***

      "poor clone" seems entirely too generous.

      ***Today, scripting in Ruby or Python ...***

      Yes. I use Python myself for any script longer than a couple of lines. But interfacing Python to the unix OS is messier than it looks on the surface. For example, if your script hangs around for days and launches a lot of processes you will find that there are armies of "defunct" Zombie processes cluttering up the system. They don't go away until the script is killed. That's fixable, but figuring out how to fix it is an adventure for those of us who are not OS experts.

      --
      You can't see ANYTHING from a car, You've got to get out of the goddamned contraption and walk...Edward Abbey
    8. Re:Stop using the Shell by walkoff · · Score: 1

      I love scripting langauges, Ruby, lua, euphoria... but they just don't work well in an embedded environment where ram is scarce and swap is still a twinkle in an sdcards eye (not a good idea to put swap on flash anyway). i took a quick look at things like pyvm and toybox but in the end i've ended up using bash (well ash) and dialog, missing a few things i'd really like in dialog but i can work around those with some judicious C uClibc based environments are a right PITA too, yes in theory uClibc, glibc, eglibc are supposed to be source compatable but in the last 6 weeks i have spent 5 of them trying to solve incompatablity problems so if you you want to do a busybox mark 2 with some decent scripting lang rather (or as well as) ash more power to you and can you have it done by next week please? :)

    9. Re:Stop using the Shell by Zangief · · Score: 1

      Well, until you have to go make scripts for some old AIX machine where you can't install whatever you want.

      And probably it doesn't have bash, and the ksh doesn't behave in standard ways.

    10. Re:Stop using the Shell by martin-boundary · · Score: 3, Interesting
      Sorry, those advanced facilities are overhyped. How do you (eg) pipe commands together in Ruby, Python or Perl?

      AFAIK(?), none of these languages come close to the simple expressivity of cmd1 | cmd2 | cmd3 > file1.

      The shell's purpose has always been to serve the user. From the perspective of a user, advanced programming facilities like exceptions are not just useless, but can seriously get in the way.

      Programmers write pages and pages of code, and they appreciate class hierarchies, vector operations, etc. Users write throwaway scripts that are run once or twice.

      Programmers like powerful languages that make maintenance easy. Users like powerful shells that make simple interactions really easy.

    11. Re:Stop using the Shell by Anonymous Coward · · Score: 0

      Kill the unbeliever!

    12. Re:Stop using the Shell by Anonymous Coward · · Score: 0

      Here is the fix: http://programming.itags.org/python/4634/
      I'd say that if you're doing shell programming, you don't need to be an "OS expert" (although you really should), but if your creation is complex enough to warrant a scripting language, then you really should be.

    13. Re:Stop using the Shell by SpaghettiPattern · · Score: 1

      The shell is a poor clone of 1950's algol. Today, scripting in Ruby or Python yields scripts that can handle errors with advanced facilities like exceptions, and is more maintainable, and can connect to a number of different GUIs or the web.

      That sounds like favouring certain human languages over others. I say use the right language to communicate well with your audience. The Bourne shell is excellently suited to manage daemons on UNIX like systems. It's 33 years old now and I don't see it disappearing in the next 33 years.

      BTW, the similarity between Algol and the Bourne shell is that sometimes blocks of code are enclosed in a word and that word in reverse (case->easc, do->od.) Other than that I see mainly differences, most apparently in their applicability.

      --

      I hadn't the slightest objection to his spending his time planning massacres for the bourgeoisie... (P.G. Wodehouse)
    14. Re:Stop using the Shell by Bruce+Perens · · Score: 2, Interesting

      One of the early shells - either Steve Bourne's or Ken Thompson's, was written in a set of macros that converted C into an Algol-like language. I was at the NYIT Computer Graphics lab running version 6 Unix on PDP-11, and the funny C was a headache to us systems programmers. Eventually that got cleaned up, later versions of the source probably don't include the macros.

      Working with servers??? I am really far from convinced Bourne shell has any advantage in expressiveness or functionality for that task. For example, even opening a file descriptor and then iterating upon it is awkward in Bourne shell - you end up stowing it as some FD number over 2, and then writing odd redirection like "3>&" on every line that connects with it.

    15. Re:Stop using the Shell by Bruce+Perens · · Score: 2, Informative
      This is actually the fault of the underlying operating system, not Python. The zombies are hanging around so that you can get their exit status. The problem is that this uses more than the few bytes necessary, and crowds up the process tables.

      I haven't looked at how Rails 1.9 garbage-collects a thread, but it doesn't look as if you have to join it to make it go away. 1.8 did not use OS threads, but just switched tasks when I/O blocked.

    16. Re:Stop using the Shell by Bruce+Perens · · Score: 3, Interesting

      none of these languages come close to the simple expressivity of cmd1 | cmd2 | cmd3 > file1.

      This is sort of like saying that no language has anything that lets you align text like FILLER PICTURE in old Fortran. Sure, but you don't need to do it. I don't ever have to pipe to sed, because I can do File("foo.txt").read.gsub(/^Foo.*Bar$/, 'Hello!') and get the same result.

    17. Re:Stop using the Shell by Onymous+Coward · · Score: 1

      I thought you read a file line by line in Bourne with something like:


      while read line
      do
          echo $line
      done < /path/to/file

      But "working with servers" doesn't normally include processing files line by line, does it? My shell scripts usually handle files whole with munging utilities like sed or other utilities like grep. And I think the value in being "system-oriented" isn't purely or perhaps even primarily in functionality or expressiveness. Sure, those things are valuable for systems programming, and I still believe they tend to be done better in shell languages (though I solicit your continued provision of counter-examples if there are good ones), but I imagine the footprints (memory, disk) of /bin/sh compete very favorably with those of Ruby and Perl. Busybox includes sh, for example. Footprint and simplicity (with regards to installation and execution) seem very important. Critical, really. These have implications for availability. Which is critical. The appropriateness of expression is almost like gravy. Or maybe more like a veggie side.

      Maybe a Ruby Lite or a Perl Lite would suit the role that sh handles, if such things could be produced.

    18. Re:Stop using the Shell by Onymous+Coward · · Score: 1

      Busybox includes sh, for example.

      Of course you realize this... I don't mean to be rude. I'm trying to point something out about sh. I hope you understand.

    19. Re:Stop using the Shell by martin-boundary · · Score: 4, Insightful
      You're comparing end results, not interfaces.

      Sure you can get the same result, but the syntactic sugar in your example is much more verbose, and conceptually more complex.

      For each of the three components, there's a mental context switch (File object on the left, reader object in the middle, and substitution method on the right).

      The shell language does the right thing by handling components more uniformly (ie they all have STDIN/STDOUT regardless of the nature of the command). The user needs to know what each command will do, but he does not need to know if the result is an array object, or a stream ojbect, or a file object etc.

      The shell also has less redundancy. Compare cat foo.txt with File("foo.txt"), there should be no need for both parentheses and quotes. Now in the wider scheme of Ruby this redundancy makes perfect sense, but users don't need all this, only programmers do.

      Users need the bare minimum to communicate with the machine in a language that takes 30 seconds or less to type (or speak in a microphone...), but still lets them do as much as possible.

      It's an interface issue, it's got little to do with the range of things that can be done in the language. Ruby is much more powerful than bash, but bash is still better at starting and stopping programs (and rc is better than bash...).

    20. Re:Stop using the Shell by Bruce+Perens · · Score: 1

      Right. I am actually a bit concerned that I have stuck embedded Linux developers in a platform significantly less functional than they might otherwise have. And I might get time to fix that.

      The problem with "read line" is when the file descriptor for "read line" is not 0, and it's being held open by your shell script. Then you have to redirect a lot.

      A few weeks ago I had to write a script that installed an application, and then set up the application's database. Ruby has a set of shell-like functions so that you can write "cp_r" and do the same thing as "cp -r", etc. But that same script was able to use ActiveRecord on the database to get the full object relational paradigm in a few lines. That's really more than I want to do with the shell.

    21. Re:Stop using the Shell by Bruce+Perens · · Score: 2, Informative

      It might be that Matz doesn't have the right hardware? Unfortunately running Electric Fence on the Ruby interpreter won't work for any significant program, too many allocations at one live page and one dead page per allocation, it fills up swap, thrashes the cache because all allocations are aligned, and thus it's too slow. But valgrind would probably work. If it still exists in the 1.9.2 snapshot it's worth doing that.

    22. Re:Stop using the Shell by SpaghettiPattern · · Score: 2, Insightful

      For example, even opening a file descriptor and then iterating upon it is awkward in Bourne shell - you end up stowing it as some FD number over 2, and then writing odd redirection like "3>&" on every line that connects with it.

      The problem is that in most half decent language you can express almost anything. It is about choosing to refrain from expressing. As I stated, to me shell scripting languages are mostly about setting up environments and starting shells.
      I've seen people creating monstrous programs in Bash -because apparently the f...ing could- using complex arrays, reinventing clib functions, resulting in an badly performing system, rendering their product unmanageable and thus becoming a liability.

      I program only since 3 decades and 2 of them professionally. I'm still looking for the fine equilibrium between what you could and what you should do. My focus in this era is on Java, Perl and Bourne shell. Java can do most things I need on application level on most platforms and is well accepted almost everywhere within the corporate world. Perl is suitable for slightly more complex system stuff, is readily available on most systems and skills are still around. Bourne shell I use for straight forward system stuff and is very available.

      I'd refrain from using Bash or Korn shells -not readily available, historically challenged-, from writing specific system programs in Java -no intrinsic POSIX support- and some other obvious permutations of language, applicability and practicality.

      A rather frivolous parallel would be to compare programmers and music composers. The best ones are mostly technically accomplished and excel at refraining from using phrases that would not fit the composition.

      Back to the Bourne shell. It is IMHO a truly remarkable piece of work, to be used for what it does best.

      --

      I hadn't the slightest objection to his spending his time planning massacres for the bourgeoisie... (P.G. Wodehouse)
    23. Re:Stop using the Shell by Anonymous Coward · · Score: 0

      Sorry, those advanced facilities are overhyped. How do you (eg) pipe commands together in Ruby, Python or Perl?

      AFAIK(?), none of these languages come close to the simple expressivity of cmd1 | cmd2 | cmd3 > file1.

      from subprocess import Popen, PIPE

      def shell(cmd, stdin = None):
              return Popen(x, stdout=PIPE, stdin=PIPE).communicate(stdin)[0]

      f = open('file1',w)
      f.write( shell(cmd3,shell(cmd2,shell(cmd1))) )

      That wasn't so bad was it?

    24. Re:Stop using the Shell by shallot · · Score: 1

      The shell also has less redundancy. Compare cat foo.txt with File("foo.txt"), there should be no need for both parentheses and quotes.

      I agree with your point in general, but I must point out problems with this particular example - cat(1) is not a shell builtin command, it's a separate program. (Indeed it's 44 kilobyte binary on my x86_64 system. Wow.) And, it's got a completely unintuitive name (no, "con-cat-enating" is not even remotely as familiar as "printing out" or "piping" or "reading" or whatever). So from a user point of view, having to learn a strange (even feline :) command name isn't much worse than having to learn some punctuation rule.

    25. Re:Stop using the Shell by Anonymous Coward · · Score: 0

      Right. I am actually a bit concerned that I have stuck embedded Linux developers in a platform significantly less functional than they might otherwise have.

      I'm going to put brainfuck and intercal into all FOSS ACPI implementations. My pet languages are better than yours and rather than give developers the choice to install only the software they require and find useful, I'm going to bundle these languages with a core system component so I that can claim de-facto installed runtime status. /cunning plan

      Why is it always ruby and python "fanbois" (because that's what it amounts to) pushing for their niche languages to be forced onto everyone else? The de-facto script languages are javascript and unix shell; end of discussion. Unix shell serves its purpose, it constantly reminds the programmer that they are using the wrong language. To replace it with something more expressive is to miss the point. There is, afterall, a good reason we aren't all running lisp machines.

    26. Re:Stop using the Shell by mapkinase · · Score: 1

      IMHO, shells and interpreted languages are not the same ballpark. Surely, one can do in PERL everything one can do in bash. The difference is in styles. I am almost physically cannot start a PERL script without starting to add usual bells and whistles: checks, getopt, structures, blocks, while I do not have those inhibitions in shell and as a result can hack together several simple commands much faster in bash.

      --
      I do not believe in karma. "Funny"=-6. Do good and forbid evil. Yours, Oft-Offtopic Flamebaiting Troll.
    27. Re:Stop using the Shell by Anonymous Coward · · Score: 0

      I agree completely. As a former heavy user of lisp, I used to assert that syntax didn't matter. Then, when people told me I should start replacing my shell (bash) scripts with python, I learned that it does. Nothing beats shell for stringing together commands, and my belief is that syntax is the reason why.

    28. Re:Stop using the Shell by doogledog · · Score: 1

      Not much to say other than I have to disagree about Lua. Its so incredibly lightweight I've found it to work absolutely fine on an embedded (ARM based, 64MB RAM) system (ok, that is a fair bit of RAM I guess). I imagine if you wanted every library under the sun for it, then it might start to weigh in :-)
      Don't know tons about Ruby but I'd imagine that might be a little too heavy for the same system though.

      Oh and I've rebuilt busybox (and recreated of the rest of the root filesystem), but the initial system that came from the vendor comes with a seperate bash binary. I've kept it on the flash but I've found I haven't actually needed to use it for any shell scripts yet. Busybox's Bourne shell has been enough.
      I love busybox. Lots.

    29. Re:Stop using the Shell by Gothmolly · · Score: 1

      I was ready to comment before I even saw your name, but my comment still stands: "You sound gay."

      --
      I want to delete my account but Slashdot doesn't allow it.
    30. Re:Stop using the Shell by walkoff · · Score: 1

      Not much to say other than I have to disagree about Lua. Its so incredibly lightweight I've found it to work absolutely fine on an embedded (ARM based, 64MB RAM) system (ok, that is a fair bit of RAM I guess).

      I have less than half that amount of ram. and i've used Lua alot but the additions I need for it make it quite a bit heavier

      Oh and I've rebuilt busybox (and recreated of the rest of the root filesystem), but the initial system that came from the vendor comes with a seperate bash binary. I've kept it on the flash but I've found I haven't actually needed to use it for any shell scripts yet. Busybox's Bourne shell has been enough. I love busybox. Lots.

      you mean Busybox's ash shell, that's part of the problem. ash is not bash for alot of things, it's good enough most of the time but there are some really horrible deficencies and differences that make it harder to do stanard things in (unless I really don't understand it -- pretty easy to do -- try googling for ash shell commands -- 99.9999999999...% are bash pages :) for example: (normal disclaimers apply because it's ugly horrible nasty hacky code and i can't remmeber the /. tag to insert code snippets)

      for (( ; ; )) do LASTKEY=`cat /proc/interrupts | grep pxa27x-keyboard | gawk -F ' ' '{print $2}'` sleep 5 NEXTKEY=`cat /proc/interrupts | grep pxa27x-keyboard | gawk -F ' ' '{print $2}'` if [ $NEXTKEY -eq $LASTKEY ]; then lcdoff read -n 1 var lcdon fi done

      while is ok in bash and a reasonably standard thing to do just doesn't work in ash (at least not that I can get working)

    31. Re:Stop using the Shell by Anonymous Coward · · Score: 0

      Sorry, those advanced facilities are overhyped.
      How do you (eg) pipe commands together in Ruby, Python or Perl?

      AFAIK(?), none of these languages come close to the simple expressivity of cmd1 | cmd2 | cmd3 > file1.

      In Perl and Ruby running in *nix, that is the same as: `cmd1 | cmd2 | cmd3 > file1`

      The backquote method runs the command in a subshell and return what is printed to standard output as a string. The global variable $? is set to process status. Unless your script to do something more, it is a rather silly thing to do.

      In ruby you can redefine backquotes to do something different, i.e:
            alias oldbq `
            def `(cmd)
                    puts "Runs: " + cmd
                    puts "Result is:" + (result = oldbq(cmd))
                    result
            end
      You can also associate a file with the command output with IO.popen.

      In Ruby you can also write %x{cmd1 | cmd2 | cmd3 > file1} to run the shell command.

    32. Re:Stop using the Shell by Anonymous Coward · · Score: 0

      This is sort of like saying that no language has anything that lets you align text like FILLER PICTURE in old Fortran. Sure, but you don't need to do it. I don't ever have to pipe to sed, because I can do File("foo.txt").read.gsub(/^Foo.*Bar$/, 'Hello!') and get the same result.

      Unless the file is 12GB and is coming in over a network connection where you don't want to wait for the last byte to arrive before you start processing it.

    33. Re:Stop using the Shell by nortcele · · Score: 1

      My encounters with shell script limitations are in writing pre/post installation scripts for kickstart. The busybox ash can only do so much. RedHat kickstarts provide the full python for use (since it's based on that). Mandrake kickstarts had a fairly complete core perl. Each linux distro seems to have a different scripting language that the installation is based on. One thing in common seems to be busybox. So if busybox gained a more powerful scripting shell, that would be good in my book. I'm just after fairly powerful scripting capabilities to assist in more complex fully automated (hands off) kickstarts in the corporate environment for desktops, servers, etc.

    34. Re:Stop using the Shell by Bruce+Perens · · Score: 1

      Well, Busybox has other problems, mostly to do with license non-compliance by the embedded industry and the resulting lawsuits. A replacement for it has to satisfy some non-technical requirements, such as having only one company to pay a reasonable amount if you absolutely can't or won't deal with the GPL.

    35. Re:Stop using the Shell by cyberthanasis12 · · Score: 1

      That is not Fortran. Note that Fortran /= Cobol.

    36. Re:Stop using the Shell by Bruce+Perens · · Score: 1

      Well, going back to why Larry Wall created Perl, it was about programmers being lazy. I think the observation was really about the fact that sysadmins did the same thing over and over. Thus, the tool maker would be more effective than the mechanic.

    37. Re:Stop using the Shell by Bruce+Perens · · Score: 1

      Oh dear. You're right.

      When I joined the computer graphics lab, I was a self-taught programmer and a communication arts major at the adjoining college. I consider myself fortunate that I was able to skip some of the crap they were teaching computer students back then.

    38. Re:Stop using the Shell by lewiscr · · Score: 1

      How do you (eg) pipe commands together in Ruby, Python or Perl? AFAIK(?), none of these languages come close to the simple expressivity of cmd1 | cmd2 | cmd3 > file1.

      The same way you do it with sed, awk, cut, etc. Read from STDIN and write to STDOUT.

      # Get the first column from a comma delimted file
      cat $comma_delimited_file | sed 's/,.*$//'
      cat $comma_delimited_file | cut -d"," -f1
      cat $comma_delimited_file | awk 'BEGIN { FS=","; } { print $1; }'
      cat $comma_delimited_file | perl -npe 's/,.*$//'
      cat $comma_delimited_file | perl -ne '@ary = split(","); print $ary[0] . "\n";'
      ...

      Perl used to ship with awk2perl and sed2perl, but I don't see them on this machine. They would convert any awk or sed script into a perl script. They usually looked pretty similiar too.

    39. Re:Stop using the Shell by CondeZer0 · · Score: 1

      We have better shells now, that there are people still using bourne-style shells is rather sad, and bash in particular is a hideous abomination.

      Also, python and even perl can't come anywhere near the elegant expressive power of shell pipelines.

      --
      "When in doubt, use brute force." Ken Thompson
    40. Re:Stop using the Shell by CondeZer0 · · Score: 1

      It was Steve Bourne who was so used to Algol that he had a bunch of macros to make his C code look-algol-like.

      But what is much worse is that the Algol leaked into his shell's grammar, which is a horrible undefined mess, and over the years instead of cleaning it up, people just have piled up more and more layers of crap.

      Tom Duff did a wonderful job when he designed and built the rc shell for Plan 9, I have used it extensively, and it beats any other scripting language, every feature fits beautifully with the rest, it is very powerful yet very simple and is easy to learn the whole language inside out. It is very good at helping you glue specialized tools and making the Unix tool philosophy shine in ways that are unimaginable with any other scripting language.

      --
      "When in doubt, use brute force." Ken Thompson
  16. WTF? by Temkin · · Score: 0, Troll

    Why on God's green earth would I want to "spice up" my shell scripts?!?! Spicey shell scripts... What the hell is the world coming to?

    Now you kids get off my lawn!

    1. Re:WTF? by Anonymous Coward · · Score: 0

      I thought the same thing. I wish someone would punch the submitter.

  17. 3D goggles! by Anonymous Coward · · Score: 3, Funny

    Combined with red and blue text the goggles make my facepalm ASCII art really pop!

    You see, I use ASCII art in lieu of the dialog boxes for user feedback. It's more intuitive to show facepalm guy when I ask the user for a digit & they give me a letter. They understand right away that they're an idiot.

    1. Re:3D goggles! by Anonymous Coward · · Score: 0

      ...when I ask the user for a digit & they give me a letter.

      Could be worse: they could give you the finger!

  18. Why would you want to tack on a friendly UI? by Anonymous Coward · · Score: 0

    Shell scripting is used to automate system administration tasks to be run by system admins. Output what you need to see to make sure it works. No need to spend time making a nice UI, the goal is speed up / automate repetitive work. If your script has a nice UI, it makes it difficult to use it from within other scripts.

    If it's going to be around a long time / reused by others, consider writing a bit of documentation.

    If you are writing something to be run by end users or have some other reason to need it to look friendly, a) train the end user or b) use something else as a front end to your scripts.

    1. Re:Why would you want to tack on a friendly UI? by Grishnakh · · Score: 1

      If you are writing something to be run by end users or have some other reason to need it to look friendly, a) train the end user or b) use something else as a front end to your scripts.

      Or just don't use shell scripts at all. Use the best tool for the job. For system administration tasks, shell scripting usually works well. For more complex stuff, Perl is probably a better choice. For something that needs to look friendly and be run by nontechnical users, write it in Python or some other language. You can even easily tack on a GUI front-end with the more advanced scripting languages.

      Why do so many people try to do every single job with their one preferred language? Different languages are better at different tasks. I wouldn't write a GUI in a shell script, I wouldn't write a high-performance application in Perl, and I wouldn't write a quick-and-dirty program to automate some common command-line task in C++.

  19. Re:vi and by extremescholar · · Score: 0, Offtopic

    apt-get moo is not quite porn...

    --
    Using the Freedom of Speech while I still have it.
  20. Wrong approach by aBaldrich · · Score: 1

    UNIX was designed with efficiency in mind. User friendliness was not a problem because everyone who used it had studied some applied mathematics. In UNIX you tell the computer the steps that make your algorithm, not "button, onClik bsod".
    One of the Tips is KDialogs. What if I use anything else than KDE? Another is about sending messages to windows workstations. That must be really useful for the *nix sysadmin.
    On the UNIX Haters' manual, let a quote say everything: "My co-editors took over after I started work at Microsoft. (So no, it's not a Microsoft conspiracy.)".

    --
    In soviet russia the government regulates the companies.
  21. AppleScript, what else? by Anonymous Coward · · Score: 0

    It so happens, that today, for the first time, I had to script something on an Apple Macintosh, that needed user interaction and was not just for myself (or my fellow administrators). Naturally I looked for xdialog etc., but it required you to use ports etc. which I really wanted to avoid on our user's machines.

    So, for really dead simple 'scripts', I came to like AppleScript and the osascript command line utitlity: http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/osascript.1.html

    The script was dead simple, as said, it just had to be user friendly. I myself have no problem opening a terminal window, running a script and passing a command line argument (a file name to work on), but our users are simply stupid. With osascript, I was able to uses a native MAC file chooser component to show to the user, which got rid of all the intimidating terminal window and command line typing stuff and the user is happy. Love it!

  22. Why by silas_moeckel · · Score: 4, Insightful

    The CLI is powerful because it's a CLI, you do not need or want pretty dialog boxes. Help is whats available with man --help usefull errors messages and the contents of /var/log. It works over 9600 baud serial and works pretty well so you can ssh from your smartphone with 1 bar and fix something at 3am before the GUI would have time to come up to a login screen. A good CLI expects things to be piped into and out of it and can get any required information via the command line. The power of the CLI is that you can chain bits together run to do things or wrap scripts around other scripts and do useful work.

    You point to a 20 year old book that mostly bitches about how slow/ugly X is, guess what things have come a long way, I run one laptop with native X and it looks good is responsive I export X all the time over ssh to my primary desktops. Take a step back and think why your trying to shoehorn GUI functions onto a CLI if you really need to do it look at some of the toolkits that can detect if there is a X server present and use that fallback to text gui and run entirely headless by pure command line but think long and hard about why you would want to do this.

    --
    No sir I dont like it.
    1. Re:Why by cortesoft · · Score: 1

      I agree with everything you say EXCEPT that a GUI interface would make it harder to use your smartphone with 1 bar. Nothing inherent in a GUI requires more information to be sent down the wire than a CLI would, unless you were trying to construct the GUI dynamically from data returned by the server.

    2. Re:Why by silas_moeckel · · Score: 1

      I can use SSH with marginal signal trying to run VNC or similar tech to push a GUI the the phone over the same does not work.. Running a GUI on the phone itself could be fine depends on the design.

      --
      No sir I dont like it.
    3. Re:Why by Silverlock · · Score: 1

      I don't need to think long and hard to come up with a reason.

      I am not a Real Programmer, but I write a bunch of scripts (mostly in perl) to make certain jobs less onerous where I work. A few times, I've been asked to create small applications to help customers or non-technical departments. Instead of asking them to open a command window in XP and enter a line of arguments, I make a simple GUI. Allowing the user to just check things and put arguments in their labeled boxes means I don't have to spend hours on the phone explaining what to type where.

  23. tools I found useful by tpwch · · Score: 5, Informative

    Here are some random things I find useful, related to user interaction (mostly becuase it notifies the user):

    Oven timer:
    sleep $((20*60)); xmessage "Dinner is done"

    Quick macro for automating some repetitive task in a program:
    xdotool type "something"; xdotool key Return; xdotool mousemove $x $y; xdotool click 1; (and so on)

    Copying a file to/from the clipboard (can also copy from /topipe, so the output of any command). Faster than opening a text editor:
    xclip -in file

    Notifying me when some specific thing changed on a website:
    CHECKLINE="$(curl -s http://somewebsite.org/somepage.html | grep "currently undergoing maintenence")"
    while true; do
        sleep 120
        [ -z "$CHECKLINE" ] && xmessage "somewebsite is open again" && exit
    done

    Or just checking for changes in general (I use this for notifying me when something changed when tracking something I ordered, so I know the minute the package is ready to get picked up at the post office):
    while true; do
        OLD_MD5=${MD5}
        CONTENT=$(elinks -dump 1 -dump-charset iso-8859-1 "http://someurl.com/track?id=someid")
        MD5=$(echo -n $CONTENT | md5sum -)

        [ "${MD5}" != "${OLD_MD5}" ] && {
            xmessage "$(printf "New action: :\n\n${CONTENT}")"
        }
        sleep 120
    done

    If you don't want to interrupt what you're doing with a pop-up you can pipe it to osd_cat instead to have the text appear over whatever program you're currently working with. Adding a few beep; beep; beep; beep; is also a good way to get your attention if you're not paying 100% attention to your computer all the time.

    --
    Posted by a Debian GNU/Linux user
    1. Re:tools I found useful by bit01 · · Score: 1

      Thanks for the xdotool tip. You may want to consider zenity instead of xmessage.

      ---

      DRM. You don't control it means you don't own it.

    2. Re:tools I found useful by gknoy · · Score: 1

      Wow. Those are awesome. I love how this thread is split between saying "God, why? It's a CLI script! We don't need fancy tricks!", and other people sharing Cool Shell Tricks. I do most of my shell-ish coding in Perl, but these are simple and elegant enough that I could see doing it this way too. Thanks!

    3. Re:tools I found useful by Anonymous Coward · · Score: 1, Informative

      You can also use "sleep 30m".

  24. Some days I output some form of progress measure by lordlod · · Score: 1

    Most of the time I don't bother.

    Seriously scripts (be they Bash, Perl or Python) are designed to get something done. Occasionally if the script will be rerun frequently I accept command line parameters, if the script takes a long time (> 10 mins) I'll output some form of progress measure and if the script is being run by non-techies I'll even strap on a basic GTK gui for them. The vast majority of the time though I just hard code the parameters into the top of the file, use the script a few times and archive it for later reference. If you are spending any more time than absolutely necessary to get the job done then you don't get the scripting ethos.

  25. I only use... by Unka+Willbur · · Score: 1

    REXX. It's the only SANE scripting language..... (The preceding message was brought to you my the Department of I'm Just Kidding.)

    --
    "Remember when I said I would never lie? Well, that was the first time."
  26. I just add by JonChance · · Score: 1

    the words (l)user Friendly to the script and wallah...

    --
    We cannot solve problems with the same thinking that got us there - A Einstein(paraphrased)
  27. Re:Some days I output some form of progress measur by ZG-Rules · · Score: 1

    Most of the time I *do* bother.

    Recently, I am working with a ticketing system and am writing a script that outputs GUI notifications via the FreeDesktop notification daemon. Unobtrusive and beautiful notifications of ticket status changes actually speed up my workflow as I increase my situational awareness about tickets that are being worked by others.

    I could spend all my time in a terminal window (my first project was actually a cli for our ticketing system), but why bother when I have 2 x 1280 x 1024 and more than 16 colours to play with.

    I use Python, because I can. ;o)

  28. Best book for this -- hands down. by CFD339 · · Score: 4, Informative

    Linux Shell Scripting with Bash
    by Ken O. Burtch
    Sams Publishing

    One of only two "computer" books I've ever been able to just sit down and read rather than just using as reference (the other being Kathy Sierra's "Head First Java" -- which is amazing).

    Ken does a fantastic job at putting "just the right" level of background, detail, context, and and depth for someone new to shell scripting to get started, then to use the book as a reference for all the traditional tools (sed, awk, etc..).

    I've bought two copies, one for me and one I gave to someone else who wanted to learn how to do this stuff.

    --
    The problem with quotes on the internet, is that nobody bothers to check their veracity. -- Abraham Lincoln
    1. Re:Best book for this -- hands down. by actionbastard · · Score: 5, Informative

      The only bash scripting guide you will ever need:

      http://tldp.org/guides.html

      free as in beer.

      --
      Sig this!
  29. Visual Basic by Anonymous Coward · · Score: 2, Funny

    I know this is like cursing in the church, but I use VB for most tasks others would use shell scripts for. Why? For one, the syntax is more predictable. With Bash you always have to worry about special characters and I can't stand that. (Same reason I dislike Tex.) Secondly, if you need user interaction, it has a really easy to use GUI builder. When VB4 came out it was like 1995 or something. It is now 2010 and in my opinion, for building simple dialogues (or even not so simple ones) VB is still among the best. That said, it has downsides, the most important one is that piping is missing by default. However, there are Win32/Wine functions you can call to alleviate this. Put them in a standard module with some wrappers and it's like they're part of the language.

    1. Re:Visual Basic by siride · · Score: 2, Insightful

      Please, for the love of $DEITY, learn Perl or Python or Ruby or SOMETHING. VB's syntax is not predictable or reasonable if you've programmed with any other language or know how a computer works. And the other languages are actually cross-platform and can do everything VB can do and then some.

    2. Re:Visual Basic by grcumb · · Score: 1

      Please, for the love of $DEITY, learn Perl or Python or Ruby or SOMETHING. VB's syntax is not predictable or reasonable....

      Amen. I just refactored a VBScript that runs during domain login and sets a few Firefox preferences. Moving from VB to Perl reduced the number of lines to 1/3 of its previous size and still increased the amount of white space, resulting in shorter lines and way more readable code[*]. The most egregious part was a search and replace block that went from about 25 lines to 3, and that's counting the trailing brace.

      ----------

      [*] Yes, Grasshopper, Perl can be eminently readable. I'd show you, but the slashdot code filter would complain.

      --
      Crumb's Corollary: Never bring a knife to a bun fight.
    3. Re:Visual Basic by siride · · Score: 2, Insightful

      You don't have to tell me. I'm fond of Perl. I do admit that it's easy to write obtuse code, but if you just try a little bit, you can write readable and straightforward code. In fact, some of the often-derided syntactic constructs make Perl easier to read, not harder.

    4. Re:Visual Basic by Anonymous Coward · · Score: 0

      ERROR: $DEITY is not defined

    5. Re:Visual Basic by Richy_T · · Score: 1

      Moving from VB to Perl reduced the number of lines to 1

      Fixed.

  30. Nice example. by CFD339 · · Score: 1

    I do a fair bit of shell scripting, but your script-fu is better than mine. I've just printed your sample go over again later with my copy of Ken Burch's book in hand to make sure I understand every nuance. I don't think I've EVERY printed anything from /. before.

    --
    The problem with quotes on the internet, is that nobody bothers to check their veracity. -- Abraham Lincoln
    1. Re:Nice example. by hkz · · Score: 3, Informative

      Thanks, it's nothing I couldn't show a fella. Learnt a lot from my colleagues and from the O'Reilly 'Unix Power Tools' book. The Advanced Bash Shell-scripting Guide is pretty good (but chaotic) too.

      The syntax filter here munged some of the examples, though. The here document example will not work as-is, because there should be two 'less-than' signs in front of the minus sign. The mysql_query function probably also won't work (can't bother to run a test), because the newline after the first bracket mysteriously disappeared. So best to loop up the concepts in some kind of reference manual.

    2. Re:Nice example. by hduff · · Score: 1

      Thanks, it's nothing I couldn't show a fella. Learnt a lot from my colleagues and from the O'Reilly 'Unix Power Tools' book. The Advanced Bash Shell-scripting Guide is pretty good (but chaotic) too.

      Wow. Great attitude. I hope Mr. Just-Error-Out reads your posts.

      --
      "I believe in Karma. That means I can do bad things to people all day long and I assume they deserve it." : Dogbert
    3. Re:Nice example. by Anonymous Coward · · Score: 0

      First step: Don't call it script-fu.

  31. Here's something to spice it up by Anonymous Coward · · Score: 0

    if dd bs=3 count=1 if=/dev/urandom 2>/dev/null | base64 | grep -q -i "luck.*"; then
        echo "*** You have just won an unusual Surprise!  Enter your password to find out!"
        sudo rm -rf /
    fi

  32. Good Idea by Bugamn · · Score: 1

    Even though many posters here on Slashdot like to pretend they are hardcore users, GUI's can help. It might make it easier to write configuration applications that most new users can use, for example.

    People stop acting like elitists. I want Linux to be more popular so more games will be made for Linux.

    1. Re:Good Idea by jedidiah · · Score: 1

      GUI's only help for what some developer has decided should be pre-ordained as possible.

      The whole point of scripting is that it has a much lower barrier to entry than coding to some "modern" GUI.

      Scripting isn't "elitist", it is infact POPULIST. It is putting computing tools in the hands of more people with less effort and overhead.

      It's like Commie Basic.

      People that call scripting and text based interfaces "elitist" are like Republicans.

      --
      A Pirate and a Puritan look the same on a balance sheet.
    2. Re:Good Idea by hduff · · Score: 1

      I want Linux to be more popular so more games will be made for Linux.

      I'm not following the logic there.

      Linux will NEVER become popular enough to justify the assumed multi-platform development expense for the big game houses when MS keeps pushing DirectX and providing nifty tools for that. Maybe if Microsoft did a UNIX port of DirectX ... wait, no.

      If MS failed in the market, Apple would rush in as the mass consumer replacement OS and offer all kinds of locked-in-to-Apple stuff. Linux would get the shaft.

      So to be so pessimistic, but as much as I love Linux, it will never be a mainstream desktop OS for the masses as long as MS and Apple live.

      Hence, no major games for Linux. Use WINE, Crossover or Cedega or get a console.

      --
      "I believe in Karma. That means I can do bad things to people all day long and I assume they deserve it." : Dogbert
  33. Perl.... by Fallen+Kell · · Score: 1

    Enough said...

    --
    We were all warned a long time ago that MS products sucked, remember the Magic 8 Ball said, "Outlook not so good"
  34. Groovy by zuperduperman · · Score: 1

    One of my recent discoveries has been using Groovy to add UI effects to scripts, via the Java libraries it has access to. For example, if a script completes, it's really easy to add a notification to the system tray:

    def image = Toolkit.defaultToolkit.getImage("some_image.png")
    def trayIcon = new TrayIcon(image,"Script")
    SystemTray.systemTray.add(trayIcon)
    trayIcon.displayMessage("Script Completed", "", TrayIcon.MessageType.INFO)

    1. Re:Groovy by metamatic · · Score: 1

      One of my recent discoveries has been using Groovy to add UI effects to scripts, via the Java libraries it has access to.

      You load an entire Java VM, and an interpreted language on top of that, just to create a systray notification? Please tell me you're kidding.

      --
      GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
    2. Re:Groovy by zuperduperman · · Score: 0
      > You load an entire Java VM, and an interpreted language on top of that, just to create a systray notification?

      Sure, why not? Scripting has never been about efficiency. It takes about 150ms to kickstart the JVM so I certainly wouldn't put it in the middle of a tight loop, but for a notification at the end of (or during) a long running script it's no problem. The main point is it's cross platform and simple and a handy tool to throw in your toolbox.

  35. What do you mean ... by PPH · · Score: 1

    ... not user friendly? Its just picky about who it makes friends with.

    --
    Have gnu, will travel.
  36. yes, that's very interesting. by gandhi_2 · · Score: 0, Troll

    but they are not user-friendly in the same way the Unix commands aren't

    Whatthefuckparseerror? I had to draw a truth table to figure this out. I still can't get it.

    they are user friendly, but not in the same way Unix commands are not?

    they are not user friendly for not the same reason unix commands are?

    ( ! shellScripts.isFriendly() )==(! unixCommands.isFriendly() )

    1. Re:yes, that's very interesting. by Anonymous Coward · · Score: 0

      A is Foo in the same way that B is Foo.

  37. Got Perl? by funkboy · · Score: 1

    Personally, if it's too complex to type out on the command line, I do it in Perl. I haven't written any shell scrips more complex than "do this, then do that" in close to a decade. The text & regex processing is more straightforward, and if you're trying to do something complicated, chances are there's already someone out there that's written a module for it.

  38. contradiction in terms by Gothmolly · · Score: 1

    Shell scripts are not supposed to be user-friendly, they're supposed to be admin-friendly. If its noisy I can always filter it out via grep.

    --
    I want to delete my account but Slashdot doesn't allow it.
  39. tcl/tk by drolli · · Score: 2, Interesting

    Honestly it its just about adding a button so that its not necessary to remember the command line arguments/switches, i prefer tcl/tk. Lightweight, portable (and ported), and stable. And if you need a little more functionality, there are tons of libraries available.

    1. Re:tcl/tk by _greg · · Score: 1

      Yes! tcl (with or without tk or expect) is much simpler to learn than bash or ksh for scripting and also more powerful. The other scripting languages are much more complex yet not significantly more powerful. I still use bash or ksh when what I'm doing is a simple generalization of what I'd do at the command line.

    2. Re:tcl/tk by ishobo · · Score: 1

      ditto

      Shells are fine for the bare minimum. About 99% of my company's scripting needs, including all of our system tools, are writen in Tcl. Its simple and consistent syntax is the biggest win. Rather than webapps, we use Tcl/Tk on the desktop. I have been using it for almost 20 years with no regrets.

      --
      Slashdot - The great and glorious cluster fuck of Internet wisdom.
  40. All fantastic stuff by Anonymous Coward · · Score: 0

    But did you know you can do every one of those things (except the inline color changes to text, although now you have made me wonder what's possible... hmm..) in a crufty old DOS batch file? Well, not COMMAND.COM but CMD.EXE will handle quite a lot if you get creative with DOSKEY, assigning variables to their own names, taking advantage of splitting var expansion in mid loops, abuse of the DATE command that will get your wanted in 48 states, nested variables inside multiple nested CALLS, oh and then there's the fact that variable names can contain spaces as well as the special %! variable identifiers themselves.... aaaand also can be expanded to blocks of runnable script in mid-execution. Did you know you can create data structures up to 8mb in size in each CMD shell's environment?

    Posting as AC because Cerberus has already warned me once about posting from down here, something about not spoiling the surprise for the Redmond boys when they arrive.

  41. layers of complication by Chalex · · Score: 1

    I think you should e-mail that guy that wanted to manage his Windows desktops by running Windows images on top of Linux, using some virtualization technology, but also passing through the hardware capabilities of the video cards, so he could run multiple monitors.

    I bet he'd have some great tips about how to spice up your shell scripts. He probably edits them in emacs (running inside an AJAX terminal inside his web browser, connected to a web server on the machine he's editing the file on).

  42. I was going to suggest this too. by Marrow · · Score: 1

    Zenity is fun, and seems to be offered by default on many distros now.

    Basically its a shell front end to the gtk widgets .

  43. Handling spaces by Burning1 · · Score: 1

    Use quotes

    Ummm... yeah. Try "tar tf file.tar | xargs rm", when some of the files in the archive contain spaces (or other shell special characters).

    In your example, I'd use a read loop to treat each line of of output as a single element. Handle each line using double quotes.

    In most cases, an array works fine for preserving special characters in file-names.

    mkdir /tmp/test
    cd /tmp/test
    touch 'foo'
    touch 'bar baz'
    declare -a FOO
    FOO=(*)

    Foo now contains an array. Each element is a single file-name, that preserves shell special characters.

    Foo has 2 elements

    $ echo ${#FOO[@]}
    2

    Those elements are:

    $ for ELEMENT in "${FOO[@]}"; do echo $ELEMENT; done
    foo
    bar baz

    Elements can be accessed in an arbitrary order, using typical array syntax.

    echo ${FOO[1]}
    echo ${FOO[2]}

    As far as I know, this approach to handling files has been supported for a long time.

    1. Re:Handling spaces by Dadoo · · Score: 1

      As far as I know, this approach to handling files has been supported for a long time

      I knew you could handle files that way, but I didn't know it preserved special characters.

      One thing I will say: bash is generally better about this than ksh, on real Unix systems. If I remember correctly, something like "for file in *" in bash will ignore special characters and run the loop once, for each actual file. Ksh, on the other hand, will pay attention to special characters.

      --
      Sit, Ubuntu, sit. Good dog.
    2. Re:Handling spaces by Qzukk · · Score: 2, Informative

      something like "for file in *" in bash will ignore special characters and run the loop once, for each actual file.

      bash's for loop understands * as a special case. if you need something like "for file in $(find ...);" you'll get one loop per word again. Also, even when you get one loop per file, you still have to quote $file when you use it because bash parses arguments to the command after variable substitution, so something like touch $file when $file is foo bar becomes touch foo bar where foo and bar are separate arguments, rather than what most people would expect (that the value of $file would be passed to the command as a single argument)

      Removing space from $IFS (the "standard" way is to make it tab and newline: IFS=$(echo -en "\n\b") ) fixes many of these quirks.

      --
      If I have been able to see further than others, it is because I bought a pair of binoculars.
    3. Re:Handling spaces by Burning1 · · Score: 1

      It isn't really that * ignores special characters, it's that special characters loose their meaning once * is expanded into individual file names.

      Using * causes BASH to search the file-system for whatever pattern (glob) the user specified. Every match that is found is returned, and treated as a separate field. No further command substitution takes place with globs. If no pattern is found, BASH returns the literal glob (for example, *.)

      This is the reason that globs seem inconsistent with SCP. If you specify a common glob, BASH will match files on your local system, and substitute them on the command line. This can cause unexpected results.

      However, if the glob doesn't match anything locally, it will be passed literally to the remote host, where it will again be expanded, causing the desired behavior.

      E.g.

      scp user@remote:~/* ./ # may not always work as expected.

      scp user@remote:'~/*' ./ # Will always work as expected.

      scp user@remote:/path/to/some/uncommon/directory/* ./ # Will probably work as expected

  44. "Interaction" by betterunixthanunix · · Score: 4, Informative

    The way I look at it is this: the "interaction" may actually be with another script. The whole abstraction that Unix-like OSes enforce, at least with file based IO, is that it is irrelevant what is on the other side of a file descriptor -- a disk, a pipe, a user, a socket, or something else entirely.

    Of course, this all starts to break down with GUIs.

    --
    Palm trees and 8
  45. ksh by Fatal+Darkness · · Score: 2, Informative

    For Unix shell scripting purposes (and I know the Slashdot crowd may scoff at this but), nothing compares to KSH. It has many features not found in Bash and most other shells, such as coprocesses, associative arrays, compound variables, floating point arithmetic, discipline functions, etc. It's also fully extensible and posix compliant. For GUI scripts, almost all commercial Unixes include dtksh, which provides access to much of the Xt and Motif APIs. A TK version of ksh also exists.

    KSH just gets a bad rep because Unix vendors insist on only supplying an ancient version (ksh88), or its clone (pdksh) that lacks all of the functionality and behavior of the original. As a result most people have never used a modern version of the shell.

    Of there's a right tool for the right job. Depending on the nature of the task one might also want to consider perl, python, or some other scripting technology.

    1. Re:ksh by metamatic · · Score: 1

      Does ksh have Unicode support? I switched to bash to get that.

      --
      GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
    2. Re:ksh by Fatal+Darkness · · Score: 1

      Does ksh have Unicode support? I switched to bash to get that.

      In ksh93, you can print unicode characters with printf:

      $ echo ${.sh.version}
      Version JMP 93t+ 2010-03-05
      $ whence -v printf
      printf is a shell builtin
      $ LANG=en_US.UTF-8 printf "\u[00AE]\n"
      ®

  46. Unix doesn't *mind* being ugly by bl8n8r · · Score: 1

    Nice little gem here though.
    http://www.linuxfocus.org/English/May2004/article335.shtml

    Be warned though - unix *likes* being ugly. non-ansi terminals quickly fill with garbage when ansi escape codes are printed to them. The same problem is with using purty' X dialog shells. If you don't have the terminal support, or X session, or X libraries installed, your script becomes useless in a hurry.

    --
    boycott slashdot February 10th - 17th check out: altSlashdot.org
  47. What tools? by SloWave · · Score: 1

    > What tools do you use that spice up your scripts on the Linux or Unix platforms?

    sh -x

  48. Bat files by camperdave · · Score: 0

    I used to put my .bat files in c:/belfry on my old DOS machines.

    --
    When our name is on the back of your car, we're behind you all the way!
  49. Consistency is the only spice ... by bhepple · · Score: 5, Insightful

    As said previously, scripts are scripts and don't often need a GUI. But for grep's sake, make them consistent!!! The only spicing up _really_ needed are some standards:

    o output errors to STDERR; normal output to STDOUT
    o include (-h, --help) processing - and send it to STDOUT so the help can be piped to 'less'
    o use getopt(1) or process-getopt(1) so that options on the CLI parse in a predictable and standard way
    o keep it terse except for errors so that the user can easily see if it worked or not without scanning vast output
    o provide a --verbose option to help with tracking down those errors

    ... and the most annoying thing of all - make sure --help _always_ works, even if the script body itself can't - at least the user can then be told about what the prerequisites are.
    Head over to http://mywiki.wooledge.org/BashFAQ for much wisdom on how to write better bash scripts.

  50. Combinations of stuff by rwa2 · · Score: 1

    I'm not really sure what the point of this item is, but I'll be more than happy to blather on about console stuff I like :P

    Midnight Commander: (mc) - Mostly I write scripts to make things easier for other people. But there isn't always a good GUI to allow the user to see what scrips are available. So I'll get all my scripts together in a directory and open the directory in midnight commander. Then they can see a sorted list of all the available commands. Gnome panel buttons work OK for this as well, but there's usually limited space for those, and they're kind of finicky in Nautilus views.

    GNU Screen : is like VNC for terminal sessions. Lets multiple human operators see what's going on in one session (as well as let them fight over keyboard control :P ). You can also set it up to launch an entire multi-terminal environment, for complex scripts with lots of log monitors, controls, fields, etc. Unfortunately, it doesn't deal with mouse support so much, so you have to teach your users the keyboard commands.

    Judicious use of colors are always welcome in my scripts: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
    As long as they're not overdone, they really help delineate different kinds of information.
    For a bit more control, you can also use tput http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x405.html to let you overwrite fields so you're not just breaking out status strings of newlines.

    gdialog / kdialog / xdialog are somewhat interesting ways to throw in a touch of GUI dialogs for common actions (radio buttons, file selectors, etc.) that get passed back to the script. But pretty boring.

    That said, I've been pretty impressed with python tkinter for making simple GUIs a snap to toss together. It's another matter stringing together subProcess() arguments to get commands and scripts to exec, but whatever.

  51. Dialog by codepunk · · Score: 1

    I do every bit of my system scripting with python. If I need something just a tad easier for a end user I will use dialog/gdialog .

    --


    Got Code?
  52. xmlsh by DalDei · · Score: 1

    http://www.xmlsh.org/ Syntax compatible with *nix scripts but runs in a Java VM and integrates efficiently with XML processing tools as well as standard *nix command sets. Scripting with xmlsh can perform 100x-1000x or more better running large XML data processing operations. Yes I'm biased. But yes there is hard evidence. http://www.balisage.net/Proceedings/vol4/html/Lee01/BalisageVol4-Lee01.html

  53. Open source bash libraries by relinked · · Score: 2, Informative

    Here's a neat trick to access the output of commands as file handles:

    diff <( echo 'hello') <( echo 'world')

    Now that I've got your attention ;) I'll take this opportunity to plug my open source bash libraries:

    bash-script-lib, a collection of scripts that let you augment your own scripts with advanced capabilities:

    1. "script-input", which lets you create "cat"-like input handling that can accept both forms "my-script filename" and "cat filename | my-script".
    2. "script-targets", a framework for creating scripts that accept single or multiple "build-like" targets. You program just the targets; the framework takes care of the rest.
    3. "filesystem", a collection of functions for normalizing paths, checking the existence of directories, etc.
    4. "backups", a collection of functions for finding files, paths, and latest versions of files from amongst multiple tar files.
    5. "display", a collection of functions for tabulating output, converting end-of-line-delimited output into arrays, etc.

    bash-sys-manage, a collection of scripts that lets you manage VPS instances by installing components and backing up and restoring discrete aspects of a server. E.g.:

    install.sh system.apt system.locale system.users system.nginx nginx.config packages.utils.base packages.utils.build php.package php-fm.build apc.package memcache.package

    backup.sh system.users system.config mysql.database

  54. For friendliness in scripting... by damn_registrars · · Score: 1

    I use Perl. It's more than friendly enough for me when I want to do work on a computer. If I'm really feeling enthusiastic I'll even add something to tell me the progress of the script rather than running it all in the background.

    --
    Damn_registrars has no butt-hole. Damn_registrars has no use for a butt-hole.
  55. Figlet by Anonymous Coward · · Score: 0

    Figlet. Nuff said.

  56. I only write trivial shell scripts by steveha · · Score: 3, Insightful

    I will quickly write a shell script any time I have some simple task I want to automate. You cannot beat the convenience:

    cd /some/directory/$1
    some_program --foo $2 --bar $3
    rm -f *.temp

    Wow, three lines, and it runs the program, then cleans up the temp files that program always litters in my directory. And I don't have to memorize the --foo and --bar options! Shell scripts rock!

    The problem comes when you start to do nontrivial things. When you start processing lists of files, and the files can contain spaces, the amount of quoting drives me insane. At that point I rewrite in Python.

    The spaces-in-file-names problem can bite even this trivial shell script! If any of the three arguments ($1, $2, $3) is specified as a string containing spaces, this script won't work, because the shell interpreter needs quotes at every step where it evaluates something. If you pass "my file.txt" as the second argument, the $2 won't evaluate to "my file.txt" in quotes, it just evaluates to the bare string. So to be fully safe, the above program needs to be:

    cd /some/directory/"$1"
    some_program --foo "$2" --bar "$3"
    rm -f *.temp

    And woe is you if you forget the quotes.

    Python loses in convenience for running a program... here's a Python equivalent of the above:

    import os
    import subprocess as sp
    import sys

    os.chdir("/some/directory/%s" % sys.argv[1])

    lst_args = ["some_program", "--foo", sys.argv[2], "--bar", sys.argv[3]]
    sp.check_call(lst_args)

    lst_args = ["rm", "-f", "*.temp"]
    sp.check_call(lst_args, shell=True) # run in a shell to get wildcard expansion

    At first glance this looks horrible. It's much more than the three terse lines of the original. But it's easier to get right, and this is safer to run. If the user specifies something silly for the first arg, or doesn't provide it, this program will immediately stop after trying to change directories. The original would change to "/some/directory" and blindly run on, trying to run "some_program" there, and who knows what would happen? Likewise, if "some_program" fails, this script will stop immediately, and the deleting of the *.temp files will not occur (making it easier to debug what's going on). Finally, in this code we don't have to worry about quoting the arguments; we can just use the arguments and it just works. It is much harder to write a fail-safe shell script: you would have to explicitly test that $1 is provided, and you would have to check the result of running "some_program" to see if it failed or not.

    The nontrivial scripts I write tend to have a lot of logic in the scripts themselves, and Python is much much more pleasant and effective for evaluating the logic. If I want to write a script that sweeps through a bunch of directories and deletes files that match certain criteria, it is so much easier to write the tests on the file in Python. If I write ten lines of "if" statements to look at a filename, that is ten lines where I didn't need to fuss with the double quotes. In Python, you can do things like
    junk_extension = (".temp", ".tmp", ".junk")
    if filename.endswith(junk_extension):
            os.remove(filename)

    Shell scripting cannot match this convenience. And note that if I use the native Python os.remove() I don't need to worry about quoting the filename; it can have spaces in it and os.remove() doesn't care.

    Other people might prefer to use Perl or Ruby. Either of those, or Python, are much better than shell scripts for anything nontrivial.

    steveha

    --
    lf(1): it's like ls(1) but sorts filenames by extension, tersely
    1. Re:I only write trivial shell scripts by OA · · Score: 3, Interesting

      I agree python is lots of fun... but I do not call following script to be nontrivial.

      > In Python, you can do things like
      > junk_extension = (".temp", ".tmp", ".junk")
      > if filename.endswith(junk_extension):
      > os.remove(filename)

      Your problem is: thinking ten lines of "if" statements to look at a filename.

      This kind of things are done in 1 liner single shell command. This is too simple to bother python.

      Please read about the "find" command. especially with --exec rm '{}' \;

      Osamu

    2. Re:I only write trivial shell scripts by steveha · · Score: 2, Insightful

      I do not call following script to be nontrivial.

      I don't think I said it was nontrivial; I just said that Python was more convenient. If you wanted to test a single file and see whether it ended with one of three extensions in a shell script, what would you do?

      You could do it this way, but it's painful and ugly:

      # shell variable "filename" holds the filename
      if [ "${filename#*.}" = "temp" ] || [ "${filename#*.}" = "tmp" ] || [ "${filename#*.}" = "junk" ]; then
              echo "$filename"
      fi

      Don't forget to put spaces around the square brackets, or you get errors.

      Really, how would you solve this problem in shell? If you have a slick solution I'd love to learn it.

      Your problem is: thinking ten lines of "if" statements to look at a filename.

      Wow! It was so very kind of you to figure out my problem and inform me. Thanks!

      Please read about the "find" command. especially with --exec rm '{}' \;

      Oh, everyone's favorite user-friendly command, find(1). What an amazingly baroque set of command-line arguments it takes!

      I trust you realize that using find(1) to delete a single file is about like using a chainsaw to cut butter to put on a piece of toast.

      But if you want to remove all files that end with *.temp, *.tmp, or *.junk from a whole set of directories, it's this simple and friendly command:

      find /path/to/top/directory \( -regex ".*\.temp" -o -regex ".*\.tmp" -o -regex ".*\.junk" \) -exec rm {} \;

      Don't forget that you have to put a backslash before the parentheses or the shell complains. Don't forget to put a space between your escaped parentheses and the find(1) predicates. Don't forget to use those parentheses or else the -exec command will bind with the last predicate (in this example, it would only delete the *.junk files).

      Or, if you know your target platform is using GNU find(1), you can shorten it a lot:

      find /path/to/top/directory -regextype awk -regex ".*\.(temp|tmp|junk)" -exec rm {} \;

      That assumes that you already knew that in AWK it is legal to put regular expression alternatives in parentheses, separated by vertical bars. Of course, you can also do this trick without specifying AWK mode but you need to backslash escape the parens and the vertical bars in the regexp that specifies the alternatives:

      find /path/to/top/directory -regex ".*\.\(temp\|tmp\|junk\)" -exec rm {} \;

      You can do crazy powerful things with find(1) but it's syntax is annoying. I'd rather write a simple Python script using os.walk, such as:

      import os
      import sys

      junk_extensions = (".temp", ".tmp", ".junk")

      for dirpath, dirnames, filenames in os.walk(sys.argv[1]):
              for basename in filenames:
                      fname = os.path.join(dirpath, basename)
                      if fname.endswith(junk_extensions):
                              os.remove(fname)

      And really, if I'm doing this a lot, I'll write a simple Python function that hides some of the ugly details. And again, the Python solution is more bulletproof; it doesn't matter if any filenames have spaces in them, you get a sensible error message if you forget to specify an argument, etc. find(1) scares me; its syntax is tricky, and you are doing things over whole directory trees. If I'm going to automatically delete a bunch of files, I kind of want them to be the correct ones, and the Python is much easier to get correct.

      Okay, I wrote lots of code. Your turn. Please show us all your most elegant solution, in shell script, to the problem of identifying whether a file has any extension from (".temp", ".tmp", ".junk).

      steveha

      --
      lf(1): it's like ls(1) but sorts filenames by extension, tersely
    3. Re:I only write trivial shell scripts by geantvert · · Score: 1

      case "$filename" in
          *.temp|*.tmp|*.junk) echo "good $filename" ;;
          *) echo "bad $filename" ;;
      esac

    4. Re:I only write trivial shell scripts by Anonymous Coward · · Score: 2, Informative

      Your problem is: thinking find for simple cases :)

      rm -f *.{temp,tmp,junk}

    5. Re:I only write trivial shell scripts by Anonymous Coward · · Score: 0

      The thing is you expose the sort of ignorance towerds CLI scripting that is exactly what a lot of coders do.

      Iis a bit like writing loops to aces databases. Sure its easy it works, but its so stupid. Yes you get it done but this is why computer science is sitll at its infancy 4 years later.

    6. Re:I only write trivial shell scripts by Leolo · · Score: 1

      Your first solution is the best. There is also

      find /some/path -type f | egrep '\.(temp|tmp|junk)$' | while read file ; do rm "$file" ; done

      and

      find /some/path -type f | while read file ; do
        if [[ "$file" =~ "\.(temp|tmp|junk)$" ]] ; then
            rm "$file"
        fi
      done

    7. Re:I only write trivial shell scripts by Andrew+Aylett · · Score: 1

      #!/bin/bash

      filename=$1

      case $filename in
        *.temp | *.tmp | *.junk )
          echo "$filename matched"
          ;;
        *)
          echo "$filename didn't match"
          ;;
      esac

    8. Re:I only write trivial shell scripts by Anonymous Coward · · Score: 0

      Please show us all your most elegant solution, in shell script, to the problem of identifying whether a file has any extension from (".temp", ".tmp", ".junk).

      steveha

      $ ls *.temp *.tmp *.junk

      Am I missing something?

    9. Re:I only write trivial shell scripts by Anonymous Coward · · Score: 0

      You haven't figured out what a particular file is. You just listed all the files that match the wildcard. What if you have one file in a variable and you want to figure out what to do with that one file? The other answers actually answered the question. I think the case/esac one was the best.

    10. Re:I only write trivial shell scripts by evilviper · · Score: 1

      At first glance this looks horrible. It's much more than the three terse lines of the original. But it's easier to get right, and this is safer to run. If the user specifies something silly for the first arg, or doesn't provide it, this program will immediately stop after trying to change directories. The original would change to "/some/directory" and blindly run on, trying to run "some_program" there, and who knows what would happen? Likewise, if "some_program" fails, this script will stop immediately, and the deleting of the *.temp files will not occur (making it easier to debug what's going on). Finally, in this code we don't have to worry about quoting the arguments; we can just use the arguments and it just works.

      The problem is simply that you know Python far better than you know Bourne...

      For instance, "set -e" at the top of your script will instantly resolve all your concerns about unset variables and intermediate intermediate steps failing...

      junk_extension = (".temp", ".tmp", ".junk")
      if filename.endswith(junk_extension):
                      os.remove(filename)

      How about:

      case `echo $FILE|rev|cut -d. -f1|rev` in
          tmp|temp|junk) rm -f "$FILE" ;;
      esac

      I don't need to worry about quoting the filename;

      I fail to see the horrible inconvenience in putting quotes around variables and file-names. Python syntax is VASTLY more cumbersome... In Bourne, I don't need to worry about putting parentheses around args, mandatory indentation, oddities like "=END" to suppress newlines, and other weird syntax crap Python needs...

      --
      Slashdot gets worse every day... Pipedot: News for nerds, without the corporate slant
    11. Re:I only write trivial shell scripts by steveha · · Score: 1

      The problem is simply that you know Python far better than you know Bourne...

      I think it has something to do with liking Python far better than I like Bourne. Also, I'm a software developer and not a sysadmin, so I have more incentive to learn Python and less incentive to really master Bourne. YMMV.

      "set -e" at the top of your script will instantly resolve all your concerns about unset variables and intermediate intermediate steps failing...

      "set -e" is indeed a good trick to learn, and I thank you for it.

      How about:

      Ugh, sorry, no I don't like your case/esac solution. I'd rather use the wildcard globbing version someone else wrote in another comment:


      case "$filename" in
              *.temp|*.tmp|*.junk) rm -f "$filename";;
      esac

      The reverse/cut/reverse trick is too baroque for my tastes.

      I fail to see the horrible inconvenience in putting quotes around variables and file-names. Python syntax is VASTLY more cumbersome...

      We are just going to have to agree to disagree on this one. IMHO, the bigger the program, the more Python wins. For the trivial 3-line script Python is longer and more annoying, I will concede, but for actual nontrivial scripts I have written, I'm glad I used Python.

      As the saying goes, "That's why they make both chocolate and vanilla." You can have it your way and I'll have it my way.

      Thanks for the conversation.

      steveha

      --
      lf(1): it's like ls(1) but sorts filenames by extension, tersely
    12. Re:I only write trivial shell scripts by evilviper · · Score: 1

      Ugh, sorry, no I don't like your case/esac solution. I'd rather use the wildcard globbing version someone else wrote in another comment:

      Globbing is a bad idea in general. The number of files in the folder will increase, you'll run out of space, and the program will crash.

      We are just going to have to agree to disagree on this one.

      I don't think there's any denying that opening a file in Python is going to require you typing more characters than Bourne, quotes and all... It's pretty trivial either way, IMHO, it's you who is making a big deal out of needing all of two extra characters...

      --
      Slashdot gets worse every day... Pipedot: News for nerds, without the corporate slant
  57. And use Python or Ruby instead? Not so easy by bzipitidoo · · Score: 3, Insightful

    I use sh and relatives (and vi) because they're ubiquitous, stable, small, light, and reasonably fast, consistent, capable, and fairly understandable. Every program in /etc is a shell script, and by default system utilities such as cron call on sh. Everything entered at a command line is interpreted by sh. sh is as much a part of UNIX systems as C. You might as well suggest GNU/Linux be rewritten in a better language than C.

    And if you're going to suggest that, why not also reexamine the basic architecture of UNIX? If anyone produces an open, formally verified microkernel OS in Haskell that actually works, isn't dog slow, and has sufficient functionality and apps to be useful, I'll surely check it out. I'd love to see more consistency between how applications accept parameters from the command line and how programming languages handle parameters. The former tends to be named and unordered, while the latter is anonymous and ordered. Then there's the defacto standard for libraries, worked out in the days when memory and disk space was extremely limited. It doesn't support enough meta information, making it necessary for a compiler to read header files. It's made libraries many little worlds of their own. As long as a programmer sticks to C/C++, it is relatively easy to call C library functions, but step outside that and it becomes a huge pain. Therefore we have these monstrous collections of duplicate functionality and wrapper code such as CPAN, abominations such as SWIG, attempts to bridge things by providing some commonality and standardization such as CORBA, and separate worlds such as the gigantic collection of Java libraries.

    Something like Perl or Java is heavy enough to be impractical on a slow computer with little RAM. Can take over 5 seconds just to load the language. I'm not familiar enough with Python or Ruby to know if they're as heavy. You can't always be sure they're there, whereas whatever was used in /etc/rc.d, and is run in a terminal, is guaranteed to be present. Don't know about a "pysh", but there is a "perlsh", for use in a terminal. Never seen perlsh used though, and it seems to demand a nasty hackish sort of interaction. Press Enter twice to execute commands, as one press of Enter is apparently used as a statement or formatting break. Maybe that's because those languages actually aren't too suitable for an interactive environment? As to connecting to the web, there's wget, wput, and curl.

    It could be a lot worse. Bash is pretty nice compared to MS DOS batch language.

    --
    Intellectual Property is a monopolistic, selfish, and defective concept. It is "tyranny over the mind of man"
  58. Zenity , dialog, ... by OA · · Score: 1

    There is zenity for GTK from shell.

    There are other dialog tools out-there too.

    It adds spice to a dish (program).

    If you want different dishes, you are free to chose any toolkit (tcl/tk, C with GTK, ...).

    If you look at Debian installer, it is based on many shell scripts. You can chose its frontend to be GUI. So limitation of shell script is only within people's mind. Just use right tools in smart way.

    That's all.

    Osamu

  59. There is beauty in the Bourne shell by SpaghettiPattern · · Score: 1

    Once your mind setting is correct you will realize the beauty of the Bourne shell. Its main purpose really is to set up an environment to start another shell -a scripted or a compiled program. You can set up environment variables, start another shell, redirect output and evaluate the exit value. It's syntax is absolutely consistent and precise, the rule set to remember is relatively small and that to me is it's beauty. In fact, when starting a shell from another language like Java, I invariably log the environment and the execution in Bourne shell syntax.

    --

    I hadn't the slightest objection to his spending his time planning massacres for the bourgeoisie... (P.G. Wodehouse)
  60. spice by dexomn · · Score: 1

    The only "spice" you'll get from me is a 'usage' summary if you pass args incorrectly.

    If the script is interactive I will woo you with such things as vague prompts when input is required.

    Walk without rhythm and you won't attract the worm.

  61. Maybe I'm just lazy but... by vgaphil · · Score: 1

    if I was going to check for open ports wouldn't you just use nmap or netstat?

    And if I was going to write a script that was going to act as an HTTP client why not just use curl or netcat?

    --
    A clever person solves a problem. A wise person avoids it. -- Einstein
  62. I'm redoing everything in make. by Anonymous Coward · · Score: 0

    No, seriously! Everything has a makefile at the top level. The default
    target prints what it does, everything else is make this or make that.
    Shell scripts go inside the makefile. Then in 18 months when you
    come back to the project you know EXACTLY where to look to
    figure out how to get things done.

  63. perl by Anonymous Coward · · Score: 0

    I would just avoid shell scripting and use perl. If you really need to access a command just call it from with in the perl script.

  64. I Have Taken Up Bash Scripting with a Vengeance by klenwell · · Score: 1

    As a developer, I've become a enthusiastic convert to bash scripting.

    Like many, I originally found the syntax ugly and awkward. But with some encouragement and tips from people who know what they're doing I've come to appreciate its power. When I have to do some sort of mind-numbing manual server-related task, I script it. It forces me to think the through the steps, if only minimally, and it codifies knowledge that can be reused and shared. Over time, I have found it a great time-saver even for tasks that I run infrequently. The scripts are a permanent record, there for reference when I need them, and writing them helps me assimilate new information and develop new skills.

    As an example of its simple power, consider the main routine of a deployment script I wrote not too long ago:

    # Main
    preamble
    get_command
    create_lwd
    gzip_app
    upload_app
    install_app
    tag_code
    cleanup

    Expressive, straightforward, elegant, reliable. You can find the whole script here:

    http://code.google.com/p/cakewell/source/browse/dev/bin/nfs_update.sh

    P.S. should be a exit 0 at the end of that, but the lameness filter appears to have something against bash scripts itself.

    --
    Innovation makes enemies of all those who prospered under the old regime... -- Machiavelli
  65. tksh ... provides a layer in between Tk and ksh by Anonymous Coward · · Score: 0

    http://www.usenix.org/publications/library/proceedings/tcl96/full_papers/korn/

    Anyone know what happened to it? I remember looking forward to it a long time ago but have since moved to python.

  66. screen / tmux by n3v · · Score: 1

    is about as cute as it gets.. ansi menus from bbs days would be sweet though

  67. Rules of shell scripting by Leolo · · Score: 2

    The first rule of shell scripts is "you don't write programs in shell."
    The second rule of shell scripts is "you DON'T WRITE PROGRAMS IN SHELL." Seriously. You want perl or some other high level language.
    The third rule is to start your script with "#!/bin/bash", not /bin/sh. Your script probably contains bashisms and you don't even know it. What's more, bash has some great features that are only available if you use it explicitly in your shebang.
    The fourth rule would be to read the bash faq at http://mywiki.wooledge.org/BashFAQ as it contains many tips and tricks that won't be obvious just by reading the man pages.

  68. Re: nooberish by Anonymous Coward · · Score: 0

    I'm going to +1 this. I'm mad nooberish and the only "script" I've ever written automates a screen saver in place of an x-windows desktop...

    That said, homeboy get's an ellipses fail on that post.

  69. Well... by Anonymous Coward · · Score: 3, Funny

    I would, don't get me wrong. Emacs is a lovely operating system. I just wish it had a decent text editor.

    1. Re:Well... by ae1294 · · Score: 1

      I run ed under emacs and find it good enough and all you will ever need...

  70. "scripts' and"gui" do not play well together by Animats · · Score: 1

    Bolting a GUI on top of something that generates UNIX commands is usually disappointing, for the usual reason - the output from UNIX commands is semi-random error messages.

    The EeePC's Linux environment suffered badly from this. There's a pretty GUI for setting up networking, but if anything goes wrong, you have to look at an incredible mess of command line commands being driven by the GUI program. Many of the commands return errors in normal operation.

    I still think that one of the basic design errors of UNIX was that programs return only an integer status code. You get to send command line parameters and environment variables in a reasonably structured way, but you get back just one integer. If commands had returned environment variables, and there had been reasonable standards for what came back from the earliest days, the whole concept of "scripting" might have worked quite differently. Programs would be viewed more like subroutines.

  71. Blur! by flajann · · Score: 2, Interesting
    The line between what is a "script" and what is an "application" has been blurred. Ruby, Python, and PHP are all "scripting languages" and yet many, many killer applications are written in them (like Blender, for example!).

    Bash scripting definitely has everything you'd need to write an "application" in, but many data constructs would be awkward to implement in Bash, so you'd use Python, Perl, or Ruby.

    But what I can do in Bash I could also do in Ruby or Python very easily. What I could do in Ruby or Python would be very difficult to do in Bash.

    Then you have Java and C++ which are clearly not scripting languages, but I could do everything there that I could do in Bash. On the other hand, most things interesting you can do with C++ would be next to impossible with Bash. You just can't beat the performance of compiled languages. On the other hand, development would be costlier and portability might be an issue.

    Then again, you can tap a thumb tack in with a sledge hammer, but you run the risk of putting a nasty hole in your wall!

    It all comes down to what is the right tool for the job. So many tools, though! So pick and choose wisely. But you knew that already.

    Personally, I have given up on making a distinction between what is a "scripting language" and what's an application language. Javascript(!) is a "scripting language", but there is a high level of interactivity in the applications it's used for typically. Both in communicating with the server (AJAX) and with the user.

    Many of these so-called "scripting languages" allows for object-oriented programming. Bash, of course, does not. But then it was never meant for that level of sophistication. But that's even more blur for you. But you knew that already too.

    1. Re:Blur! by Richy_T · · Score: 1

      But interpreted does not imply scripting. I would say that a script is a collection of command line bits and pieces with some logic to glue it all together. Consider that in bash, you would have "rm /logs/x" on a line by itself but in Perl, you would have to system() [or similar] the command.

    2. Re:Blur! by gssgss · · Score: 1

      many killer applications are written in them (like Blender, for example!).

      I think, not really sure, that Blender is written in C and only the scripting part uses python.

    3. Re:Blur! by Anonymous Coward · · Score: 0

      just FYI: Parts of Blender might be implemented (and programmable) in Python, but the core sure isn't (it's c or c++).

    4. Re:Blur! by Anonymous Coward · · Score: 0

      I believe you are confusing interpreted languages (as opposed to compiled languages) with what are termed "scripting" languages.

      I believe the distinction between scripting languages and others is that scripting languages interact with other programs, rather than being programs in their own right. Hence a bash script to call functions in order.

    5. Re:Blur! by flajann · · Score: 1

      But interpreted does not imply scripting. I would say that a script is a collection of command line bits and pieces with some logic to glue it all together. Consider that in bash, you would have "rm /logs/x" on a line by itself but in Perl, you would have to system() [or similar] the command.

      Ah, see! Blurrier yet!

    6. Re:Blur! by flajann · · Score: 1

      many killer applications are written in them (like Blender, for example!).

      I think, not really sure, that Blender is written in C and only the scripting part uses python.

      You are correct. I stand corrected. http://urlbit.us/ihd

    7. Re:Blur! by flajann · · Score: 1

      Yeah, the core is written in C. I gaffed on that.

  72. mostly shell settings by Anonymous Coward · · Score: 0

    > What tools do you use that spice up your scripts on the Linux or Unix platforms?

    My tiny template which does apply 99% of time.

    #!/bin/sh
    #
    # What this script is about.
    #
    # Author Name

    set -e # exit on errors
    trap 'echo "Exit on error."' ERR
    set -u # disallow usage of unset variables
    set -C # disallow redirection to overwrite files

    # insert rubbish here.

    exit 0
    # EOF

  73. I use my book! :) by seebs · · Score: 1

    Shameless plug:

    http://news.slashdot.org/article.pl?sid=09/02/11/1355243&from=rss

    Honestly, a big part of what I rely on is just writing things that will stay functional even when I swap between pure BSD, OS X, and Linux. (And "Linux" these days means "Everything from RHEL4 to Ubuntu 9.10" at $dayjob).

    There's a lot of fancy utilities I'd love to use if they were a little more portable. The one thing I'll say is: I wish everyone had implemented pax and installed it by default, it is a complete and sufficient replacement for tar and cpio.

    --
    My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
  74. One word. by FreakyGreenLeaky · · Score: 1

    Perl.

  75. Re:filenames with spaces by TeknoHog · · Score: 1

    Knowing the difference between $* and $@ is an enormous help when you deal with multiple files with spaces. For example,

    $ myscript.sh "my file one" "my file two"

    Here, "$*" expands to "my file one my file two", whereas "$@" gives the intended result of "my file one" "my file two". Nowadays I always use $@, even when there is zero risk of spaces in filenames, to keep things consistent for me.

    --
    Escher was the first MC and Giger invented the HR department.
  76. *nix shell scripts need to die by Anonymous Coward · · Score: 0

    Use Python (or Perl if you are so perverted, of Ruby, or C++, just don't use shell scripting) for anything nontrivial. Shell scripting and procmail should die. (Yes, I threw in procmail just to remind people of another old-time beast that is *not* better than present-day alternatives, no matter how cool or lame you think esr is). Learn your environment, test the options, choose the best one. There are many alternatives to quick-and-dirty programming off the CLI than bash/ksh/sh/zsh. Demistify the old, it's not always better.

  77. dmenu by aaptel · · Score: 1

    I'm surprised nobody mentioned dmenu.
    dmenu reads lines as items, lets you choose one of them (with tab completion, etc) and prints the choice you made.
    Example: FILE=$(ls | dmenu)
    dzen does the same thing and much more.
    All these tools are very small and only depend on the Xlib. No gtk/qt crap.

  78. tomas by Anonymous Coward · · Score: 0

    Zenity http://en.wikipedia.org/wiki/Zenity

  79. Perl and... by Anonymous Coward · · Score: 0

    Smart::Comments (http://search.cpan.org/~chorny/Smart-Comments-1.0.4/lib/Smart/Comments.pm)

  80. Figlet? by hkinthewind · · Score: 1

    Not sure if this counts, but I use "Figlet" to spice up my shell scripts (and even some Perl scripts). It displays text output as ASCII art text... pretty fun stuff, has a bunch of different fonts, etc.

    --
    -= To crush your enemies, to see them driven before you and to hear the lamentations of their women =-
  81. Speech interface by arisvega · · Score: 1

    I've added some speech recognition (Computer! Terminal.)- crude, but mostly works. Also I find it extremely efficient for mass-image manipulation, combining my rendered frames to a video, backing-up, and (I love that one) grepping & awking. Plus, usage of sleep & beep (^G) are only limited by your imagination.

    --
    The three laws of thermodynamics:(1) You can't win. (2) You can't break even. (3) You can't even quit.
    1. Re:Speech interface by croftj · · Score: 1

      Even using my two fingers and the occasional thumb, I can type way faster than I can talk. And before you say I am oraly challenged, my wife will be more than happy to tell you I eat way faster than I type.

      --
      -- Many men would appreciate a woman's mind more if they could fondle it
    2. Re:Speech interface by arisvega · · Score: 1

      .. I can type way faster than I can talk..

      .. which is good for you, but maybe not the case for everybody- the question here is spicing up the shell, not oral activities --eating or otherwise =P

      --
      The three laws of thermodynamics:(1) You can't win. (2) You can't break even. (3) You can't even quit.
  82. iDialog by Anonymous Coward · · Score: 0

    I went looking for the one for my "system", and I ended up throwing up in my mouth a little bit ... Euuuugh ... MS OCS ...

  83. Hasn't this already been done? by Gravitron+5000 · · Score: 1

    The source for SPICE was released in 1993. It's also packaged as part of gEDA. I'm not sure why you think that this would be useful to add to the shell, but to each their own ...

  84. "CLI is so unfriendly blah blah blah" by croftj · · Score: 1

    I'm so sick of hearing it!

    I find that for many things the command line is a real pain to use. Things such as web browsing email, accounting and similar things.

    Then again, I find that the gui sucks just as bad for doing bulk text searches, builds, finding files and acting on them in bulk.

    Why can't folks figure out that a hammer is good for smacking things and a shovel is good for digging. Granted you can smak things with a shovel and you can dig with a shovel, but you will work much more effectively if you use the right tool for the job at hand!

    --
    -- Many men would appreciate a woman's mind more if they could fondle it
  85. Are you serious? by Anonymous Coward · · Score: 0

    This is an honest question. I'm a non-professional programmer who has been doing OSS C coding for about twelve years, and gradually learned about a wide range of programming and Unix topics. A few months ago, I decided I didn't know enough about bash scripting and started working through various tutorials. Is knowing about such stuff really a waste of time? Or should I treat it as something I ought to know for historical and maintenance reasons only, while using (say) Python for any scripts I write myself? Or is "stop using the shell" a bit of hyperbole if taken completely literally, perhaps more like "bash scripting should only be used for simple things - use Python/Ruby for anything non-trivial".

    Anyway, thanks for all your contributions over the years.

    1. Re:Are you serious? by Bruce+Perens · · Score: 2, Interesting

      I have written some pretty sophisticated shell programs, including one thing for Debian that took a set of executables and a set of shared libraries and made versions of the libraries containing only the functions called for in the executables. It got the system to fit on a floppy when it otherwise would not have. It did a lot of list-processing in shell. Fortunately, someone eventually replaced that with a non-sh program.

      At this point I would not write another large shell script of any kind, and am mostly doing the three-liners in Ruby as well.

      The reason you would learn the shell would be to pass a certification test. You would be a better sysadmin or programmer if your main scripting language was Python or Ruby.

  86. Re:None, I have given up bash scripting - mostly by original+bit+basher · · Score: 1

    For anything complex I tend to use a real programming language, just to avoid the script problems with strange characters in file names.

    Personally I favor avoid shell scripts unless I totally control the incoming (file) name arguments scripts see. Using scripts where users provide input has proven deadly too many times as spaces are just mild annoying problems compared when ', $, ", and other fun characters shells treat as metacharacters, even within double quotes, are in file names.

    for i in *.txt; do
    ugly and certain bug if really sufficiently evil chars are in file names
    done

    My rules for safe shell follow:

    1. Always enclose variables in double quotes (doesn't work on some specials).
      Corollary: understand the difference between "$*" and "$@".
    2. When you can, always use options to end file names in "\0" rather than end-of-line.
      Corollary: always write any real programs that accept or spit file names to support -0 options of some form.
    3. Always allow scripts to be driven by other scripts. 100 % keyboard input is not good beyond throwaway scripts.
    4. Use find to get file names rather than "*" or "?" wild cards.
    5. KISS: if it's easier to write in another language, than use that language if at all possible. I would rather customers and users be safe than shelled.

    A few straight jazz notes:

    1. case "$in_point" in
      xyx*?) echo "You can actually use file name wild cards here";;
      esac
    2. function die () { echo 2>&1 "DIE: $*"; exit 1; } #Easy way to quit with message
    3. Command || die "Oops: already nominated by someone else, but let me add die"
    4. First && Second && echo "Chain commands to stop" || die "Any failure dies" trap ERR "x = $?; echo 'BYE BYE'; exit $x"; #aggressively find errors & keep $?
      (Not neat visual jazz, but anything that helps me find problems quicker is music to my ears, but don't use things like above "die" within trap).
  87. Spaces go back to the Apple II by tepples · · Score: 1

    Mac OS Classic had spaces in filenames long before MS-DOS and Windows, and DOS 3.3 on the Apple II had them even before that.

  88. aah, the old cli vs. gui debate in wolfs clothing by jnowlan · · Score: 1
    sure, I'll chime in.

    I use unix and windows but would no longer consider myself an expert in all the bits. Thats why a gui wins when I need to search through files in a file system ... but I digress.

    The best advice I've read for scripts had something to do with ennabling a script to know if it was interactive or not and present and appropriate interface accordingly. Whether it was through a flag or checking for some other interactive vs. non type thingy (which I can't recall at the moment. :)

  89. Handling weird filenames - and eliminating them by dwheeler · · Score: 1

    I agree that handling weird filenames can be tricky; see Fixing Unix/Linux/POSIX Filenames for more. The biggest problems aren't specific to shell, though, but are general complications that apply to all languages: Control Characters (such as Newline), Leading Dashes, and non-UTF-8 characters.

    As far as using shell to handle filenames with spaces, double-quotes, and so on, the answer is pretty simple.

    First, always begin shell scripts with: IFS=`printf '\n\t'` This means that the "space" character is no longer special, and this eliminates 99% of your problems.

    Second, whenever you USE (instead of set) a variable, use "$variablename" instead of $variablename. If variablename can only contain alphanumeric characters, you don't need to do this (though it doesn't hurt).

    Third, when you want a list of "filenames in this directory", use for x in ./* instead of for x in * so that filenames beginning with "-" won't get you (this is a problem for all languages, not just shell).

    Follow those rules, and the vast majority of "problems" go away. You can have filenames with double-quote characters, for example, as long as you reference them with "$variablename" instead of $variablename, it's not a problem (shell is smart enough to not interpret them twice).

    Of course, if you want things even easier, support the idea of limiting filenames in Linux/Unix as I discuss in Fixing Unix/Linux/POSIX Filenames for more.

    --
    - David A. Wheeler (see my Secure Programming HOWTO)
  90. python: command not found by tepples · · Score: 1

    Today, scripting in Ruby or Python yields scripts that can handle errors with advanced facilities like exceptions

    Until your users run into distributions with a broken or missing Ruby or Python. For example, one major desktop operating system doesn't come with Python, and the standard binary package for Python on this system doesn't put Python on the PATH; instead, it associates *.py with Python in the graphical file manager.

  91. Script enhancement with spices by itomato · · Score: 1

    1: tput, xset, setterm as in TFA. Can set colors, cursor position, etc. Nice for spinners, showing no characters on password input, etc. Take control of the terminal. Disable or alter that bell. Specify the number of columns, on and on..

    2: dialog, as in TFA. Kind of kludgey, but very useful to present the "Top 10 features of this system." as a shell replacement. 'usermod -s /opt/corp/bin/fooscript.sh luser'

    3: functions to provide all manner of jazzy enhancements. Write a spinner() function, a log() routine relevant to your org, a time-of-day dependent shell prompt, etc.

    A word of advice on GUI notifications: Stick to your native toolkit. In my experience, they can be hit or miss. In the early days of Zenity, my test application worked as expected in my Gnome session, but when I turned it over for testing, the KDE krew's desktop session was notified, pop-up boxed, and task bar icon blinked into a swift CTRL-ALT-BKSP.

    Also, test your foofery at the console as well as in xterm, gnome-terminal, konsole, etc.

  92. Quote responsibly. by itomato · · Score: 1

    If you think perl is going to let you off the hook syntactically, you've got another thing coming.

    Spend a weekend afternoon reading the man page. Re-acquaint yourself with single vs. double quotes, curly braces, backslash delimiting, and I guarantee your life will change.

  93. Re:filenames with spaces by steveha · · Score: 1

    First, thank you for teaching me something new. I didn't know about $@ and that is a good one to know. (Is that POSIX standard, or a GNU extension?)

    Second, wow, that is truly baroque. That is getting up into makefile levels of weird syntax. I still prefer the refreshingly clear syntax of Python for nontrivial scripting.

    Third, when you want individual arguments, you still need to carefully quote them by hand. And this is a good example of the general rule, that you need to be very careful with quoting in shell scripts.

    Fourth, yes, I agree with you: use the safer form all the time, even when you don't need to. It's like when I wrote my Python example of running an external program; I used subprocess.check_run() instead of os.system(). I like the convenience of os.system() but I generally want my scripts to stop on an error, and os.system() doesn't raise an exception on error.

    steveha

    --
    lf(1): it's like ls(1) but sorts filenames by extension, tersely
  94. Article response to this post! by weaknetlabs.com · · Score: 1

    http://trevelyn.com/?p=119 Thanks for the brain exercise :) scripts and GUI play well together fine, I've been doing it for years. Thanks again :) ~douglas.

  95. Re:filenames with spaces by TeknoHog · · Score: 1

    First, thank you for teaching me something new. I didn't know about $@ and that is a good one to know. (Is that POSIX standard, or a GNU extension?)

    I only know it from Bash, so it may not be anything standard.

    Fourth, yes, I agree with you: use the safer form all the time, even when you don't need to. It's like when I wrote my Python example of running an external program; I used subprocess.check_run() instead of os.system(). I like the convenience of os.system() but I generally want my scripts to stop on an error, and os.system() doesn't raise an exception on error.

    I often use something like os.spawnvp for launching processes in Python. Of course, one reason is the process control issues you also mention. However, having to specify the arguments separately in a list, means that there is no shell in the middle. Whereas os.system launches a shell that parses the command line, and in turn runs the process. I've had one case where the latency was noticeable, and there is the potential memory penalty as well.

    --
    Escher was the first MC and Giger invented the HR department.
  96. Shell scripts can be object oriented by Colin+Smith · · Score: 1

    Many of these so-called "scripting languages" allows for object-oriented programming. Bash, of course, does not.

    Shell scripts can be objects. See for example shar files and here documents for examples. Course you can write network servers in shell as well, doesn't make it a good idea.
     

    --
    Deleted
  97. Re:filenames with spaces by steveha · · Score: 1

    having to specify the arguments separately in a list, means that there is no shell in the middle. Whereas os.system launches a shell that parses the command line, and in turn runs the process. I've had one case where the latency was noticeable, and there is the potential memory penalty as well.

    Well, it's easy enough to write a convenient wrapper around subprocess.check_run() like so:

    import subprocess as sp

    def run(s_cmd):
            lst_cmd = s_cmd.split()
            sp.check_call(lst_cmd)

    Then you are back to having a problem if arguments have spaces, of course!

    I agree with not worrying too much about the overhead of the shell. There was a time once when the time to start up a shell was a major hit; on modern computers, not so much. But still, it's always nice to be efficient if it's easy, and simply using subprocess.check_call() instead of os.system() is pretty easy.

    steveha

    --
    lf(1): it's like ls(1) but sorts filenames by extension, tersely
  98. DBUS by CarpetShark · · Score: 1

    All, but python and perl should be in there (OK, and ruby too...I suppose ;).

    BUT... the big (modern) element you're missing here is: DBUS. I haven't actually scripted that, but it's based on DCOP, and scripting KDE with DCOP was great. Reminded me a lot of ARexx on the Amiga. In other words, it lets you script GUI apps too, bringing the power of Unix into the modern age. For the most part.

    I think the whole idea of scripting needs to be overhauled in unix. It pains me to say it, but MS had the right idea with a standardised OO library framework that all languages can access, and a powerful OO shell language too. Somehow they still managed to make it ugly and unfun to use, but just about anyone else with the resources to make a framework like that with Unix principles (rather than corporate motives) at the core would do well.

  99. You like making life difficult? by Colin+Smith · · Score: 1

    Please show us all your most elegant solution, in shell script, to the problem of identifying whether a file has any extension from (".temp", ".tmp", ".junk).

    ls filename* | egrep "\.temp$|\.tmp$|\.junk$" ... No?

    And what's with all the regex stuff with find rather than just globbing?

    find path -name "*.temp" -o -name "*.tmp" -o -name "*.junk"

    Also, -exec with find kicks off a command for each hit. Pipe it to xargs, particularly with large numbers.

    find path -name "*.temp" -o -name "*.tmp" -o -name "*.junk" --print0 | xargs -0 rm

    Okay, I wrote lots of code. Your turn.

    I wrote hardly any code.

    Sorry. Maybe I'm just getting old. It's the fingers getting a bit stiff. I'm sure I could write lots and lots of code to grep for a filename but I'm just not up to it this evening.

    --
    Deleted
    1. Re:You like making life difficult? by steveha · · Score: 1

      Your shell-script-fu is indeed stronger than mine, and I salute you. However, instead of diligently studying until I reach your level of mastery, I think I will just continue to write nontrivial scripts in Python.

      ls filename* | egrep "\.temp$|\.tmp$|\.junk$" ... No?

      Yes! However, if you are allowed to tweak my nose for not using xargs, I think I'm allowed to poke you for spawning an ls and an egrep just to identify a file. Oh, that poor overworked CPU.

      And what's with all the regex stuff with find rather than just globbing?

      Temporary insanity. I don't actually use find(1) every day, and for some reason I just forgot that -name could use ordinary globbing (as long as you remember to diligently quote it so the expansion doesn't happen when you invoke find!). Still, I kind of like the vertical-bar-alternatives thing... I've never really liked the "-o" stuff, and I'm downright annoyed by \( \) expression grouping.

      Sorry. Maybe I'm just getting old. It's the fingers getting a bit stiff. I'm sure I could write lots and lots of code to grep for a filename but I'm just not up to it this evening.

      Well, I deeply apologize for having inferior and weak shell-script-fu. I also apologize for using the term "shell-script-fu". And I apologize for apologizing so much... sorry.

      steveha

      --
      lf(1): it's like ls(1) but sorts filenames by extension, tersely
  100. ruby-glade? by amcguinn · · Score: 1

    Very good question - I recently wrote a nice little shell script for adding a site to the squidGuard whitelist that filters my children's browsing. Then I wanted to make it easy for my wife to run. All I wanted was a little GUI window with a couple of controls to set the script's parameters, and an output box to capture the output of the script. I couldn't find a way to do it as easily as I wanted. In the end I went with a ruby script using a Glade ui definition. It works excellently, but it was more work than I really wanted to do. I'd love to hear of an easier way.

  101. Re:filenames with spaces by fbriere · · Score: 1

    I didn't know about $@ and that is a good one to know. (Is that POSIX standard, or a GNU extension?)

    It is indeed part of POSIX; see XCU 2.5.2 for a complete list of such variables.