tags:

views:

245

answers:

3

[Edit] I've summarized the answer to the following below, the error lies in the line:

[Edit] if [$1 ne $value]; then


I'm trying to pass a value to a command:

#!/bin/bash
for value in $(mycommand $1)
do
    echo Found $value
    if [$1 ne $value]; then
        echo No match!
    if
done

But if I type in the following to execute the script:

#./myscript 25

I get the error:

Found somestuff
./myscript: 25: command not found

What I'd like to do is pass in the first argument of the script ("25" in the example above) and send it to the command 'mycommand'.

How can I do this?

A: 

I don't find any issue with that script.

$ more x
#!/bin/bash
for value in $(echo $1)
do
    echo Found $value
done
$ sh x 28
Found 28
$

What is mycommand doing exactly ?

Stefano Borini
+1  A: 

Is that the complete myscript? I tried your script as written and got no such error:

$ ./myscript.sh 25
Found somestuff
$

If I add a $1 to the end of the script:

$ ./myscript.sh 25
Found somestuff
./myscript.sh: line 6: 25: command not found
$

Update to your edit: When using the [ command, you need to add some extra space, and also use -ne:

if [ $1 -ne $value ]; then

The [ command is often implemented as a soft or hard link to the test command, for example:

$ ls -l `which [`
lrwxr-xr-x    1 root     root            4 May 16  2006 /usr/bin/[ -> test

The manual page for test will give more information about the valid expressions.

Greg Hewgill
You botha re correct my script as posted was incomplete.
Jamie
Thank for suggesting the "ls -l `which [`" - it pointed to a busybox implmentation. Is there another construct I can use for the 'if' statement that I could use as an alternative?
Jamie
Thanks for your help. I'll post my answer ...
Jamie
Using the busybox implementation should be fine. Make sure you put a space after the [, just as you would with any other command.
Greg Hewgill
A: 

Greg pointed me in the right direction, namely:

  • add spaces around the [ ] in the if statement, I didn't know they were commands
  • the program test doesn't take 'ne' as an argument.

My corrected script is:

!/bin/bash
for value in $(mycommand $1)
do
    echo Found $value
    if [ $1 != $value ]; then
        echo No match!
    if
done

Many thanks.

Jamie
Put a hyphen before the "ne" so you have `-ne`. Also see the Bash `man` page and http://mywiki.wooledge.org/BashFAQ/031 for reasons why `[[` is better than `[` especially concerning the reduced need to quote arguments.
Dennis Williamson