2

I m very new to shell scripting and writing a script for a project. I am having a problem while doing "stat" on a file name, to check size, which has spaces in it. The problem is that I can not write the command directly, and first I have to store it in a variable then I have to execute it via that variable. For example my script is:

##test.sh
###Start
OIFS=$IFS

IFS=$'\n'

filename=$1

a=stat
b=-c  
c=%s
d=${filename}

CMD="$a $b $c $d"

result=`$CMD`

echo "Size is:"$result

IFS=$OIFS
###END

I have set IFS=$'\n' to pass the file name having space in it as a parameter. when I execute it, then I get:

[root@abhargava ~]# ./test.sh dirLevel1/file\ Level1.txt
./test.sh: line 9: stat -c %s dirLevel1/file Level1.txt: No such file or directory
Size is:

Because of IFS, I think shell is treating the command as a single unit without splitting it into parts and if I remove that setting of IFS then it says:

[root@abhargava ~]# ./test.sh dirLevel1/file\ Level1.txt
stat: cannot stat `dirLevel1/file': No such file or directory
stat: cannot stat `Level1.txt': No such file or directory
Size is:

So it is treating the parameter as two different files. I can not use "$@" also because I am getting the file name from some other logic of listing files in a directory like

for i in 'find ${arg} -type f'
do
calling the test.sh
done

Please help me out ASAP..!! Thanks in advance....!!

nerdwaller
  • 18,014

3 Answers3

0

I realise this is an old thread, but I found a nice article that solves this problem when you are piping your filename into stat. Namely you need to use xargs together with the -d flag (for delimiter) in order to specify another delimiter to use OTHER than whitespace. When I specify my delimiter to be a newline '\n' then it works for me!

Credit goes to this article: https://shapeshed.com/unix-xargs/

0

I agree with Ignacio, keeping Bash scripts simple is the best approach to take. From that, I have simplified the script to allow it to work with spaces. To allow it to handle spaces, enclosing the filename in quotes has allowed the script to deal with spaces in the filename.

##test.sh
###Start

result=`stat -c %s "$1"`

echo "Size is:"$result

###END
DaveSB
  • 1