我写了一个用于打印书籍的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",它们都是假的。
这怎么可能?
如果$first
和$last
为空,[ $first -o $last ]
将被评估为[ -o ]
,这不是你想要的。
您应该改用[ "$first" -o "$last" ]
,它等效于[ "" -o "" ]
。
永远不要在不引用变量的情况下使用变量(除非你知道自己在做什么):大多数时候结果会出乎意料。
此外,在命令行中以交互方式测试奇怪的行为:只需输入[ $a -o $b ] && echo y
即可快速查看正在发生的事情并能够使用您的变量。