help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Help With School Assignment, Learning Bash Scripts


From: Eric Blake
Subject: Re: [Help-bash] Help With School Assignment, Learning Bash Scripts
Date: Fri, 07 Nov 2014 14:39:23 +0100
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.2.0

On 11/07/2014 02:05 PM, Greg Wooledge wrote:
> On Thu, Nov 06, 2014 at 05:18:00PM -0500, nick wrote:
>> Here is my code so far:
>> !/bin/bash 
>> shopt -s extglob nullglob
>> dir=$1
>> for file in "$dir"/!*(.old)
>> do
>>     [[ $file == *.old ]] || mv -- "$file" "$file.old"
>> done    
> 
> The extended glob is not quite right.  If you want to match "all files
> except those that end with .old" it should be "$dir"/!(*.old) instead.

But what about dot files?  Your extended glob fails to move
"dir/.hidden" to "dir/.hidden.old"; while on the other hand you probably
don't want to move "dir/.." (for what I hope is an obvious reason).  But
correctly writing a loop that includes hidden files but excludes the two
special '.' and '..' entries is hard in globs (without extglob, it
requires 3 globs; extglob might make it possible in 2, but it still
starts looking like line noise).

> 
> Also, this makes the check for *.old inside the loop redundant.
> 
> I have to agree with Eduardo that your teacher is asking you to do things
> the old, dumb, wrong way.  This is tragically common from what I've seen,
> and unfortunately is no longer surprising....
> 
> You'll have to choose between intentionally writing things in the broken
> way that your teacher wants in order to get good grades, or doing things
> the right way and explaining to your teacher why they are right, and
> risking bad grades.  (In this particular case you can demonstrate that
> the teacher's method fails on filenames with spaces in them.)

Or do both - include a comment of one way to do things, next to an
implementation of the other, along with comments detailing the
differences between the two approaches and why you went with the
uncommented approach.  If nothing else, you have a stronger leg to stand
on when you prove you did your research and have an argument for your
choice.

And just for fun - here's a one-liner that does the same, but covers all
hidden files (and requires GNU find, but works with POSIX sh instead of
requiring bash):

#!/bin/sh
find "$1" -mindepth 1 -maxdepth 1 \! -name '*.old' -exec mv {} {}.old \;

Anyone who claims there is only "one right way" in solving a computer
problem is probably wrong.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]