gpt4 book ai didi

linux - Linux shell 脚本中的逻辑或错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:00:58 25 4
gpt4 key购买 nike

我写了一个打印书籍的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 即可快速查看正在发生的事情并能够使用您的变量。

关于linux - Linux shell 脚本中的逻辑或错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21390840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com