Page 1 of 1

White space in a program

Posted: Sat Feb 26, 2022 8:46 pm
by don570

I noticed something interesting regarding white space....
The following code didn't work as I thought.

Code: Select all

A=$(basename "$FILE")
mkdir -p  ""$A".extracted"

I thought that ""$A".extracted" would be the smart thing to do to protect white space in a file's name.
I wanted a folder to be created based on the file name.
However what it did was create MULTIPLE folders !!!! if there was some white space in the file name.

So I changed to following and it worked properly.

Code: Select all

A=$(basename "$FILE")
mkdir -p  "$A".extracted

The entire script is here...
http://forum.puppylinux.com/viewtopic.php?t=5291


Re: White space in a program

Posted: Sun Feb 27, 2022 10:56 pm
by misko_2083
don570 wrote: Sat Feb 26, 2022 8:46 pm

I noticed something interesting regarding white space....
The following code didn't work as I thought.

Code: Select all

A=$(basename "$FILE")
mkdir -p  ""$A".extracted"

I thought that ""$A".extracted" would be the smart thing to do to protect white space in a file's name.
I wanted a folder to be created based on the file name.
However what it did was create MULTIPLE folders !!!! if there was some white space in the file name.

So I changed to following and it worked properly.

Code: Select all

A=$(basename "$FILE")
mkdir -p  "$A".extracted

The entire script is here...
http://forum.puppylinux.com/viewtopic.php?t=5291

This would work too:

Code: Select all

A=$(basename "$FILE")
mkdir -p  "$A.extracted"

Unless the filename starts with "-" character.
Then the command will interpret it as an option.

Code: Select all

basename "-filename.ext"
basename: invalid option -- 'f'
Try 'basename --help' for more information.

mkdir -p "-filename"
mkdir: invalid option -- 'f'
Try 'mkdir --help' for more information.

So it's a better to separate the parameters with --

Code: Select all

basename -- "-filename.ext"
-filename

mkdir -p -- "-filename"
echo *
-filename

Working with filenames is tricky. ;)


Re: White space in a program

Posted: Fri Mar 04, 2022 11:28 am
by user1234

Or you can use-

Code: Select all

mkdir -p  "\"$A\".extracted"

But the resultant directory will be "filename". extracted.

The reason your code didn't work was that that doing ""$A".extracted" would be equal to $A".extracted", since '''' is like opening and closing quotes ('' and then '').


Re: White space in a program

Posted: Fri Mar 04, 2022 4:33 pm
by don570

Back to my first post...

mkdir -p ""$A".extracted" results in multiple folders being created if there is white space in the filename.
That's my warning.
___________________________