bash and strings

Garrett Cooper youshi10 at
Thu Nov 15 21:17:42 PST 2007

Girish Venkatachalam wrote:
> On 03:43:24 Nov 16, jhall at wrote:
>> Everyone,
>> I'm sure this is easy, and I am making it harder than it is.
>> I am being supplied a list of files, and need to create the files and
>> directories to hold them, but I cannot figure out how to take the string
>> apart.
>> For example, I am given
>> /usr/local/scripts/
>> I need to create the /usr/local/scripts directory and then create
>> Any suggestions would be greatly appreciated.
> There is always more than one way to skin a cat. :)
> Perhaps you will like mine.
> DIR=`dirname $path`
> FILE=`basename $path`
> /bin/mkdir -p $DIR
> cd
> touch $FILE
> You can put this in a loop with path as loop variable.
> Best of luck!
> regards,
> Girish
A better way would be to quote the string variables, i.e.:

DIR=`/usr/bin/dirname "$path"`
FILE=`/usr/bin/basename "$path"`
/bin/mkdir -p "$DIR"
touch "$FILE"

Otherwise dirname and basename will choke on non-escaped characters 
(i.e. spaces), mkdir/touch will make funky directories / files, 

Just watch out for '$' chars in $path...

Welcome to the wonderful world of [in]secure shell scripting :).


More information about the freebsd-questions mailing list