【问题标题】:Comparing variables in shell scripts比较 shell 脚本中的变量
【发布时间】:2013-12-14 23:05:13
【问题描述】:

我有一个涉及 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

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

使用 shell sh 或 ksh-

#./test.sh
./test.sh[2]: a:  not found
completed

使用 shell bash-

#./test.sh
./test.sh: line 5: a: command not found
completed

我尝试将if $X = $Y 行括在括号和双括号中,然后我回来了

[a:  not found  

[[a:  not found

如果我将变量 X 和 Y 更改为数字“1”,我会得到同样的结果-

./test.sh[2]: 1:  not found

我试过用单引号、双引号和反引号括起来。

感谢任何帮助。

【问题讨论】:

标签: shell scripting sh ksh solaris-10


【解决方案1】:

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

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

if [ "$X" = "$Y" ]; then …

if [[ "$X" = "$Y" ]]; then …

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

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

¹ $X [[ … ]] 语法除外。

【讨论】:

  • This endorses 这个解决方案适合来这里寻求答案的人,我只是没有 ksh 来测试它。空间很重要。
【解决方案2】:

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

soExample.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}"

输出:

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

ksh 版本:

user@foo:/tmp $ echo $KSH_VERSION
@(#)MIRBSD KSH R48 2013/08/16

【讨论】:

  • 你应该双引号所有变量插值。如果$X 包含空格,您将开始看到错误消息,或者更糟糕的是,用户输入作为代码运行。
  • @tripleee 好点,代码已更新。你有没有一个参考,它说双引号所有变量插值是 ksh 最佳实践?
  • 没有专门针对 ksh 的,但是当您知道 shell 的工作原理时,它就相当明显了。除非您特别需要对变量的值进行空格分割和通配符扩展,否则它需要被引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2015-12-03
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多