karmag: Stylized face based on Dreamwidth logo (Default)
[personal profile] karmag posting in [community profile] command_liners

Hey, a command line community? That's a pretty neat thing to have.

So to introduce myself, here's something I figured out pretty recently. It's in one of those eyes-glazing-over parts of the shell man page (but I had a specific problem to solve so I had to figure it out). Behold! It is a piece of "parameter expansion" magic:

$ TEST='foo:bar' ; echo ${TEST%:*} ${TEST#*:}
foo bar

Ooh, exciting! No wait, it's not. But here's the problem I had: How can I loop over pairs of values in a script or one-liner?

The solution I came up with looked something like this:

$ for f in url1:filename1 url2:filename2 url3:filename3;
do URL=${f%:*}; FILENAME=${f#*:} ;
; done

...and so for each pair, URL and FILENAME gets set to their respective portion. (And you'll be glad to learn that I got my Youtube-mediated crime drama fix in the end.)

Date: 2010-11-02 08:14 pm (UTC)
foxfirefey: A guy looking ridiculous by doing a fashionable posing with a mouse, slinging the cord over his shoulders. (geek)
From: [personal profile] foxfirefey
Ooooh I did not know this and it is useful!

Date: 2010-11-03 12:25 am (UTC)
jld: (vessel)
From: [personal profile] jld
Other thing: #blah and %blah will take off the shortest match, while ##blah and %%blah will remove the longest. Also, all of these just give the unchanged value if there's no match.

This can be useful for things like ${foo##*/}, or for generalizing those pairs to more things.

Date: 2010-11-03 03:27 pm (UTC)
pne: A picture of a plush toy, halfway between a duck and a platypus, with a green body and a yellow bill and feet. (Default)
From: [personal profile] pne
In any case, when using bash-isms, use a shebang of #!/bin/bash - some people use #!/bin/sh under the assumption that everyone uses (certain distributions of) Linux /bin/sh is bash.

If you want bash, say so explicitly, then you won't be bitten on systems where /bin/sh is the original sh, or something else like the Almquist shell (ash/dash).

Date: 2010-11-03 02:40 am (UTC)
afuna: Cat under a blanket. Text: "Cats are just little people with Fur and Fangs" (Default)
From: [personal profile] afuna
Oh hmm!

*tucks it into her toolbox for future reference*


command_liners: A command line prompt with a blinking cursor after it, green against black. (Default)
Command Liners

September 2014

1415 1617181920

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Sep. 20th, 2017 10:03 pm
Powered by Dreamwidth Studios