2014-01-27 65 views
0

我已经写了印刷书籍shell脚本:逻辑或错误的Linux 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 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 

即条件 “$第一-o $最后” 是真实的。但是如果在这个地方分别检查“$ first”和“$ last”,它们都是错误的。

这怎么可能?

回答

3

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

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


切勿使用变量,而无需引用它们(除非你知道你在做什么):结果将是意想不到的大部分时间。

此外,在命令行中交互式测试怪异行为:只需输入[ $a -o $b ] && echo y即可快速查看正在发生的事情并可以使用变量进行游戏。

+1

POSIX标准建议不要使用'-o'因为这个原因,并建议使用'[...] || [']代替'[... -o ...]'。 – chepner