質問

I am trying to execute the following shell script

#!/bin/csh
if [[ $# != 1  ||  $1 != "first" && $1 != "second" ]]
then
    echo "Error: Usage: $0 [first|second]"
    exit 1
fi

but I am getting an error:

if: Expression Syntax.

I have no idea what's wrong with that syntax. It looks fine to me. please help.

役に立ちましたか?

解決

The C shell (csh) doesn't have the variable $#. In fact, in csh the arguments passing, if statement etc are fundamentally different to say, ksh or bash. All your code looks like a bash code but your shebang line contains csh. So if you want to use bash then change it to:

#!/bin/bash
if [[ $# != 1  ||  $1 != "first" && $1 != "second" ]]
then
    echo "Error: Usage: $0 [first|second]"
    exit 1
fi

Or if you really wanted to use csh then you have re-write the code to:

#!/bin/csh
if ( $#argv != 1  ||  $1 != "first" && $1 != "second" ) then
    echo "Error: Usage: $0 [first|second]"
    exit 1
endif

他のヒント

If you use C-shell you should write

#!/bin/csh
if( $# != 1  ||  $1 != "first" && $1 != "second" ) then
    echo "Error: Usage: $0 [first|second]"
    exit 1
endif

Your version works for Bourne-like shells like sh, bash etc.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top