Linux shell脚本中的逻辑OR错误

时间:2014-01-27 20:20:20

标签: linux shell

我为打印书写了一个shell脚本:

#!/bin/sh
if [ -z "$1" ]
then
    exit 1
fi
filename=$1
options=""
mode="color"
first=""
last=""
pages="All pages from"
shift
until [ -z "$1" ]
do
    if [ $1 = "gray" -o $1 = "grey" -o $1 = "grayscale" -o $1 = "greyscale" ]
    then
        options=" -o ColorModel=KGray"
        mode=$1
    elif [ $1 = "from" ]
    then
        shift
        first="$1"
    elif [ $1 = "to" ]
    then
        shift
        last="$1"
    fi
    shift
done
if [ $first -o $last ]
then
    pages="Pages"
    if [ $first ]
    then
        pages="$pages $first"
        first=" -f $first"
    else
        pages="$pages 1"
    fi
    if [ $last ]
    then
        pages="$pages to $last"
        last=" -l $last"
    else
        pages="$pages to last"
    fi
    pages="$pages from"
fi
echo -n "$pages $filename will be printed in $mode mode. If it's OK, put paper in your printer and press ENTER. Else press CTRL+C. "
read ack
pdftops$first$last -expand $filename - | psbook | psnup -2 > tmp.ps
psselect -o tmp.ps | lpr$options
echo -n "Wait for the end of printing, then take printed pages, put them back in printer to print on other side and press ENTER again."
read ack
psselect -e -r tmp.ps | lpr$options
rm tmp.ps
exit 0

当我将此代码保存到文件“print-book”并运行时:

print-book test.pdf gray

我明白了:

Pages 1 to last from test.pdf will be printed in gray mode. If it's OK, put paper in your printer and press ENTER. Else press CTRL+C

即。条件“$ first -o $ last”是真的。但如果在这个地方单独检查“$ first”和“$ last”,它们都是假的。

这怎么可能?

1 个答案:

答案 0 :(得分:3)

如果$first$last为空,[ $first -o $last ]将被评估为[ -o ],这不是您想要的。

您应该使用[ "$first" -o "$last" ],相当于[ "" -o "" ]


永远不要在没有引用的情况下使用变量(除非你知道你在做什么):大多数时候结果都是意外的。

此外,在命令行中以交互方式测试奇怪的行为:只需输入[ $a -o $b ] && echo y即可快速查看正在进行的操作并能够使用您的变量。