在编写 bash 脚本以帮助使用 Imagick 的 convert
命令创建宝丽来缩略图时。我遇到一个问题。虽然,我设法解决了这个问题(实际上,因为 convert
足够灵活),但我仍然想知道如何在没有这种特定解决方法的情况下解决这个问题。
基本上,bash 脚本将获得一个可能包含空格的标题值。我想将该标题用作 convert
的参数。如果标题为空 (''),我将不会使用选项 '-caption' 进行转换命令。像这样:
CAPTION="Is this Cute?" # The actual value will be tacked from the parameter of this bash.
IN_FILE="resources/puppy.png"
OUTFILE="resources/puppy_polaroid.png"
# If CAPTION is not empty, reformat CAPTION
if [ "$CAPTION" != "" ]; then CAPTION="-caption \"$CAPTION\""; fi
# otherwise, do not use '-caption' add all
COMMAND="convert $CAPTION \"$IN_FILE\" \"$OUTFILE\""
echo "Command: $COMMAND" #This echo a value command
`$COMMAND`
回显回显可以复制的值命令可以粘贴在终端中并运行。但是 bash 没有运行。我该怎么做?
注意:如果是convert
,-caption ""
会完成这项工作。我知道这一点,目前使用它作为解决方法。
在此先感谢您的帮助。
编辑:根据答案,这是现在对我有用的代码。
... # Get CAPTION and GRAVITY from parameters
if [ "$CAPTION" != "" ]; then ARGS_CAPTION=(-caption "$CAPTION"); fi
if [ "$GRAVITY" != "" ]; then ARGS_GRAVITY=(-gravity "$GRAVITY"); fi
if [ ! -f "$IN_FILE" ]; then echo "The input file does not exist: '$IN_FILE'"; exit; fi
if [ "$OUTFILE" == "" ]; then OUTFILE=${IN_FILE%.*}-${IN_FILE#*.}-polaroid.png; fi
ARGS=("${ARGS_CAPTION[@]}" -thumbnail 480x480 -border 5x5 -pointsize 60 "${ARGS_GRAVITY[@]}" +polaroid -thumbnail 120x120)
echo convert "${ARGS[@]}" "$IN_FILE" "$OUTFILE";
convert "${ARGS[@]}" "$IN_FILE" "$OUTFILE"
我希望这对那些寻求类似解决方案的人有用。
最佳答案
I'm trying to put a command in a variable, but the complex cases always fail!
Variables hold data. Functions hold code. Don't put code inside variables! There are many situations in which people try to shove commands, or command arguments, into variables and then run them. Each case needs to be handled separately.
...
- I'm constructing a command based on information that is only known at run time
The root of the issue described above is that you need a way to maintain each argument as a separate word, even if that argument contains spaces. Quotes won't do it, but an array will. (We saw a bit of this in the previous section, where we constructed the addrs array on the fly.)
If you need to create a command dynamically, put each argument in a separate element of an array. A shell with arrays (like Bash) makes this much easier. POSIX sh has no arrays, so the closest you can come is to build up a list of elements in the positional parameters. Here's a POSIX sh version of the sendto function from the previous section:
关于Bash:变量值中的空格稍后用作参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2249821/