Mark
Mark

Reputation: 630

SH script - passed variable (file name) with space

I am honestly a bit disappointed in myself but I've spent a few hours trying to search this down successfully. The topic has been covered in a number of threads but I just can't get to a resolution.

I have a 'sh' script (on a busybox or I'd use full bash).

The script is called externally and passed 3 variables ($1, $2, $3) where:

$1 directory of file
$2 not used
$3 name of file including directory

I'm trying to get the file size (stat is not available) so I'm trying to use du:

pseudo:

filesize=$(du $3 | awk '{ print $1 }')

I just can't get the script to process filenames with spaces correctly. I've tried quoting and escape quoting to no avail. At the command prompt I can inject the \ to handle white space for du.

Help is appreciated.

Upvotes: 0

Views: 171

Answers (3)

Mark
Mark

Reputation: 630

I am very thankful for those who took the time to provide some ideas on this issue. After a long time and much effort, it was determined that the busybox implementation was the culprit.

Everything provided above was valid provided a more current version of bb was used (or any full distro). Unfortunately it took significant trial and error to get to the cause.

Upvotes: 0

John
John

Reputation: 316

Try

    filesize=`du "$3" | awk '{ print $1 }'`

Upvotes: 1

shx2
shx2

Reputation: 64318

Double-quoting works is sh.

sh-3.2$ f="a b"
sh-3.2$ echo aaaa > "$f"
sh-3.2$ ls -l "a b"
-rw-r--r--  1 xxxx  xxxxx  5 May 23 xx:xx a b
sh-3.2$ du "$f"
8   a b

Upvotes: 2

Related Questions