Bash script trickery

I have come up with a convoluted way to remove duplicate numerical entries from a bash array and sort the results (i.e. creating a sorted set). I invite others to give a a better solution… but this works and that is what is important for a throwaway script:

seeds2=`echo -e ${seeds[@]}| awk '{if (!x[$1]++) print $1"\\\\n\\n"}'`; unset seeds; seeds=( `echo -e $seeds2 | sort -bg` )

where $seeds is the array to sort – with each entry ending in a “\n”… awk needs inputs line by line (as does uniq, but remember uniq is only for removing adjacent repeating lines).



9 comments ↓

#1   Bob on 02.17.06 at 3:26 pm

Joel, you are one sick, sick puppy!

I just used bash to make this script:

if test -x some_file ; then exec some_file ; else exec some_other_file ; fi

I put the first semi-colon after the ‘then’ which of course leads to an incredibly value error message. And so I waste 5-10 minutes just getting an if statement to work!

Every time I come back to bash/sh I have forgotten the syntax and I am reminded how I hate shell scripting with a passion!

I hope for the sake of our children that shell scripting is buried in the future.

#2   Joel on 02.17.06 at 5:22 pm

i initially was just using bash to run replications of a stochastic simulation, but then it got more convulted and I’ve had to learn alot of bash stuff. The Advanced Bash scripting guide is my friend 🙂

oh and instead of “test” you can just do:

if [ -x some_file ]; then …

😉

#3   Bob on 02.19.06 at 12:40 pm

Yeah I found out about the [ ] thing after using an embedded system that had ‘[‘ as a symlink but it wouldn’t handle ‘]’. So now I always use test instead of hiding behind those braces…

#4   Joel on 02.19.06 at 1:39 pm

ah, fair enough!

#5   Skarnz on 02.21.06 at 5:42 pm

Uuuh….

I live in a giant bucket…?

#6   Joel on 02.21.06 at 6:09 pm

My spoon is too big!

#7   Bob on 02.22.06 at 4:00 pm

I am a banana!

Hmm I also noticed I wrote ‘value’ instead of ‘vague’. ‘Value’ is one of those words I type so much in code that my fingers type it without even noticing.

#8   Peter on 10.15.08 at 11:49 am

Hi. I came across this post while searching for a solution and I finally came up with this:

UNIQUE_ELEMENTS=”`for ELEMENT in ${ARRAY[@]}; do echo ${ELEMENT}; done | sort -u`”

#9   Joel on 10.15.08 at 5:08 pm

Thanks Peter! Much more elegant 😉

Leave a Comment