[英]How to use OR condition inside tcsh if statement
我試圖在tcsh shell的IF語句中使用OR條件。 相同的語句在CSH中有效。
if [ "$1" == "hi" -o "$2" == "hello" ];then
echo hi
else
echo hello
fi
[35] % sh -x test hi hi hello
+ test hi hi hello
test[7]: hi: A test command parameter is not valid.
+ exit 1
[36] % sh -x test hi hi
+ test hi hi
test[7]: test: Specify a parameter with this command.
+ exit 1
[37] % sh -x test hi hello
+ test hi hello
test[7]: test: Specify a parameter with this command.
+ exit 1
[38] % sh -x test hi hello
+ test hi hello
test[7]: test: Specify a parameter with this command.
+ exit 1
[39] %
請提出可以做什么?
[44] % uname -s
HP-UX
[45] %
[45] % echo $SHELL
/bin/tcsh
[46] %
cat new_test.txt
if ([ $1 == 1 ] || [ $2 == 1 ])
then
echo $1 and $2
fi
./new_test.txt 1 1
./new_test.txt: ==: A test command parameter is not valid.
./new_test.txt: ==: A test command parameter is not valid.
cat suggested.sh
if (($1 == 1) || ($2 == 1)) ; then echo "$1 and $2" ; fi
./suggested.sh 1 1
./suggested.sh: 1: not found.
./suggested.sh: 1: not found.
有一些困惑:
[
是。 像這樣修改第一個腳本:
#!/bin/sh
if [ "$1" == "hi" -o "$2" == "hello" ]; then
echo hi
else
echo hello
fi
這意味着,如果該腳本可執行,則它將使用/bin/sh
進行解釋。 但是,如果使用命令強制外殼程序:
% sh -x test hi hi
+ '[' hi == hi -o hi == hello ']'
+ echo hi
hi
% tcsh -x test hi hi
if [ hi = hi -o hi = hello ]
if: Expression Syntax.
then
then: Command not found.
%
您會發現使用錯誤的Shell會導致某些語法錯誤。
如果要編寫tcsh腳本,這是一個解決方案:
#!/bin/tcsh
if ( "$1" == "hi" || "$2" == "hello" ) then
echo hi
else
echo hello
endif
if
語法不同,因為tcsh具有內部測試功能,而標准bourne shell沒有該功能。 布赫納殼測試是使用外部命令作出test
,其具有一個別名[
。 因此,您可以閱讀手冊中有關test
語法的文檔:
SYNOPSIS
test expression
[ expression ] ...
s1 = s2 True if the strings s1 and s2 are identical. ...
expression1 -o expression2
True if either expression1 or expression2 are true.
對於tcsh的if
,請閱讀tcsh的手冊(或csh的父手冊):
if (expr) command
If expr (an expression, as described under Expressions) evalu-
ates true, then command is executed. Variable substitution on
command happens early, at the same time it does for the rest of
the if command. command must be a simple command, not an
alias, a pipeline, a command list or a parenthesized command
list, but it may have arguments. Input/output redirection
occurs even if expr is false and command is thus not executed;
this is a bug.
if (expr) then
...
else if (expr2) then
...
else
...
endif If the specified expr is true then the commands to the first
else are executed; otherwise if expr2 is true then the commands
to the second else are executed, etc. Any number of else-if
pairs are possible; only one endif is needed. The else part is
likewise optional. (The words else and endif must appear at
the beginning of input lines; the if must appear alone on its
input line or after an else.)
Logical, arithmetical and comparison operators
These operators are similar to those of C and have the same precedence.
They include
|| && | ^ & == != =~ !~ <= >=
< > << >> + - * / % ! ~ ( )
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.