比较shell脚本中的变量

use*_*191 8 shell scripting ksh sh solaris-10

我有一个涉及shell脚本并比较其中的值/变量的项目.我在这里和其他地方看过比较变量,我已经尝试了所有给出的各种例子,但我遇到了一些不像广告那样的东西.操作系统是Solaris10

我创建了以下脚本作为学习经历 -

#!/bin/ksh

stest()
{
if $X = $Y
then echo they're the same
else echo they're notthe same
fi
}


X=a
Y=a

stest

echo completed
Run Code Online (Sandbox Code Playgroud)

我不断得到以下的一些变化 -

使用shell sh或ksh-

#./test.sh
./test.sh[2]: a:  not found
completed
Run Code Online (Sandbox Code Playgroud)

使用shell bash-

#./test.sh
./test.sh: line 5: a: command not found
completed
Run Code Online (Sandbox Code Playgroud)

我已经尝试if $X = $Y用括号和双括号括起来,然后我回来了

[a:  not found  
Run Code Online (Sandbox Code Playgroud)

要么

[[a:  not found
Run Code Online (Sandbox Code Playgroud)

如果我将变量X和Y更改为数字"1",我会得到相同的东西 -

./test.sh[2]: 1:  not found
Run Code Online (Sandbox Code Playgroud)

我试过用单引号,双引号和反向引号括起来.

任何帮助表示赞赏.

Gil*_*il' 11

之后if,您需要一个shell命令,就像其他地方一样.$X = $Y被解析为shell命令,意思$X是被解释为命令名称(假设变量的值是单个单词).

您可以使用[命令(也可用test)或[[ … ]]特殊语法来比较两个变量.请注意,括号内部需要空格:括号是shell语法中的单独标记.

if [ "$X" = "$Y" ]; then …
Run Code Online (Sandbox Code Playgroud)

要么

if [[ "$X" = "$Y" ]]; then …
Run Code Online (Sandbox Code Playgroud)

[ … ]适用于任何shell,[[ … ]]仅适用于ksh,bash和zsh.

请注意,您需要围绕变量¹使用双引号.如果省略引号,则变量将拆分为多个单词,并且每个单词都被解释为通配符模式.这不会发生在内部[[ … ]],但右侧也=被解释为通配符模式.始终在变量替换周围加上双引号(除非您希望将变量的值用作文件名匹配模式的列表,而不是字符串).

¹ 除了在$X[[ … ]]语法.


jav*_*e42 4

这个 KornShell (ksh) 脚本应该可以工作:

so示例.ksh

#!/bin/ksh 

#Initialize Variables
X="a"
Y="a"

#Function to create File with Input
#Params: 1}
stest(){
    if [ "${X}" == "${Y}" ]; then
        echo "they're the same"
    else 
        echo "they're not the same"
    fi
}

#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
stest #function call#
echo "completed"
echo "Exiting: ${PWD}/${0}"
Run Code Online (Sandbox Code Playgroud)

输出 :

user@foo:/tmp $ ksh soExample.ksh
Starting: /tmp/soExample.ksh with Input Parameters: {1:  {2:  {3:
they're not the same
completed
Exiting: /tmp/soExample.ksh
Run Code Online (Sandbox Code Playgroud)

ksh版本:

user@foo:/tmp $ echo $KSH_VERSION
@(#)MIRBSD KSH R48 2013/08/16
Run Code Online (Sandbox Code Playgroud)

  • 您应该用双引号引用所有变量插值。如果“$X”包含空格,您将开始看到错误消息,或者更糟糕的是,用户输入将作为代码运行。 (2认同)