Jamie
Jamie

Reputation: 7441

Passing BASH arguments

[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?

Upvotes: 1

Views: 2306

Answers (3)

Jamie
Jamie

Reputation: 7441

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.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994619

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.

Upvotes: 1

Stefano Borini
Stefano Borini

Reputation: 143925

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 ?

Upvotes: 0

Related Questions