-1

I am debugging a bash script (on ubuntu) to obtain an image file block size using stat. The result from stat is correct at the command line but not when passed into a variable (as it is in the script).

If I use the stat command at the command line, I get what I want (the number of blocks, %b):

stat --format=%b image.png

Output, e.g.: 72

But if I pass the same into a variable (at the command line or in a script), like so:

b = $(stat --format=%b image.png); echo $b

I get this output:

 15:16:57 up  3:47,  0 users,  load average: 0.52, 0.58, 0.59
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT

Yet, when I "x check" my script with /bin/bash -x ../script.sh, the variable b, defined as above, except that the image filename is passed as a variable, is shown to hold this value:

+ b = 328
 15:47:39 up  4:18,  0 users,  load average: 0.52, 0.58, 0.59
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT

What did I miss?

This is my script:

#!/bin/bash

## Run in a folder containing image files to return the html <img /> links.

touch img_reflinks.html

generate_list ()
{
  ls  .| egrep '\.png|\.svg|.jpg|.jpeg|.tiff'
}

for f in $(generate_list)
do
    str=''
    style=''

    # the filename prints correctly:
    echo "$f"

    # this is the problematic assignment, as in CL:
    b = $(stat --format=%b "$f")

    style="\"width:" + "$b" + "px;\""

    str="<img src=\"" + "$f" + "\", style=" + "$style" + "/>\n"

    echo "$str" >> img_reflinks.html
done
MCC
  • 109
  • 1
  • 5
  • Aren't you getting a pile of "command not found" type errors for this script? – that other guy Apr 07 '19 at 20:34
  • Please explain the downvotes as they are totally [unwarranted](https://stackoverflow.com/help/privileges/vote-down). Thanks. – MCC Apr 11 '19 at 20:39
  • in bash no spaces are allowed surrounding = sign during assignment so its `b=$(stat --format=%b "$f")` and not `b = $(stat --format=%b "$f")` – Scott Stensland Aug 23 '21 at 19:31

1 Answers1

0

No space allowed in a variable declaration; so instead of

b = $(stat --format=%b image.png); echo $b

do

b=$(stat --format=%b image.png); echo $b

And instead of

ls  .| egrep '\.png|\.svg|.jpg|.jpeg|.tiff'

do :

for i in *.png *.svg *.jpg *.jpeg *.tiff; do
    # ...
done
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223