Domanda

It's been a while since I've scripted in bash so I made a small script to test things out. This is my script (the quoted text is some Dutch, doesnt really matter):

#isingelogd
if[$#=0]
then
    echo "Geef user-id's op!" 1>$2 ; exit 1
fi
for uid in $*
do
    if who|grep $uid >dev/null
    then
            echo $uid is ingelogd
    else
            echo $uid is niet ingelogd
    fi
done

If I try to run it it tells me the following:

bash-3.2$ ./isingelogd
./isingelogd
./isingelogd: line 3: if[0=0]: command not found
./isingelogd: line 4: syntax error near unexpected token `then'
./isingelogd: line 4: `then'

If I check my version with bash -v I'm running 3.2 which I thought supported square brackets.

Has someone had a similar problem and found solution?

È stato utile?

Soluzione

Look at your errors:

bash-3.2$ ./isingelogd
./isingelogd
./isingelogd: line 3: if[0=0]: command not found
./isingelogd: line 4: syntax error near unexpected token then'
./isingelogd: line 4:
then'

See that command not found? you have an error in your script.

The [..] are actual commands, and like all commands, they need to be separated by white spaces. The = is a parameter to the [ command and also needs to be surrounded by white space. Change line #3 to this:

if [ $# -eq 0 ]

Since $# and 0 are numeric, you should use -eq which compares to numbers and not = which compares strings.

Try these commands:

$ ls -li /bin/test
$ ls -li /bin/[

You'll see they have the same inode number. They're links. (Yes, the [ and test are builtins into the shell, but they are linked builtin commands).

$ man test

will give you all of the various tests that [ can do. Again, note the difference between -eq vs. = and -gt vs. >.

Note the following:

if [ 54 > 123 ]
then
    echo "54 is greater than 123"
fi

This will print out "54 is greater than 123". This won't:

if [ 54 -gt 123 ]
then
   echo "54 is greater than 123"
fi

Altri suggerimenti

a.bash works for me in Mac. Content of a.bash is the following :

#!/bin/bash

if [ $# == 0 ]; then
    echo "Usage da da do" 
fi

export A=$1
echo $A

then execute with the following :

\# ] ./a.bash

   Usage da da do
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top