LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Command that works on BASH promp but not from a shell script! (http://www.linuxquestions.org/questions/linux-general-1/command-that-works-on-bash-promp-but-not-from-a-shell-script-505305/)

ChrisScott 11-27-2006 02:18 PM

Command that works on BASH promp but not from a shell script!
 
Hi all, anyone feel like enlightening a beginner-shell-scripter?

The section of code I'm stuck on is supposed to take a (unspecifed) number of field titles - for a latex table. This is my code as it stands:

field=""
fieldnumber=0

until [ "$field" = "done" ] ; do
read field
fieldnumber=$((fieldnumber + 1))
field$fieldnumber="\"$field\""
done

Here's the bit that really confuses me! When I run the scrip and enter, say, 'example' BASH returns:

field1="example": command not found

obviously if I type that command directly into the BASH prompt it works fine. I thought that a shell script should work in exactly the same way as if you type it straight into the prompt - so why the error?

Any ideas would be appreciated. Cheers, Chris.

makyo 11-27-2006 03:40 PM

Hi, Chris.

Most interpreted languages provide 2 features that control scanning. One is some kind of escape mechanism that says "don't look at the enclosed text for anything special"; this is often a set of quote marks. The other, often eval, says "look at this chunk again".

For your code, I added the eval and an eval of an echo. The echo, being a print statement, is often your best debugging tool:
Code:

#!/bin/sh

# @(#) s1      Demonstrate eval.

field=""
fieldnumber=0

until [ "$field" = "done" ] ; do
        read field
        fieldnumber=$((fieldnumber + 1))

        eval field$fieldnumber="\"$field\""
        eval echo field$fieldnumber="\"$field\""
done

which, when run, produces:
Code:

% ./s1
1
field1=1
2
field2=2
done
field3=done

If you are going to post code here often, please use the CODE tags -- highlight, then click "#".

For this problem, you might want to consider using an array, q.v.

Best wishes ... cheers, makyo

( edit 1: addition )

ChrisScott 11-27-2006 03:55 PM

Thanks Makyo. I hadn't noticed the CODE button - I'll use it in future!

C

berbae 11-27-2006 04:05 PM

eval field$fieldnumber="\"$field\""

/bin/bash 11-27-2006 07:11 PM

FYI, to increment a variable, this works in bash.
((fieldnumber++))

$ AA=1;((AA++));echo $AA
2


All times are GMT -5. The time now is 07:00 PM.