Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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....!!

share|improve this question
    
Updated your formatting to make it more legible, please double check to verify that I didn't displace anything by accident. –  nerdwaller Feb 4 '13 at 5:37

2 Answers 2

up vote 0 down vote accepted

BASH FAQ entry #50: "I'm trying to put a command in a variable, but the complex cases always fail!"

share|improve this answer
    
Solved my problem using an array instead of single variables Thank You very much... :) –  Anil Bhargava Feb 4 '13 at 13:18

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.