Bash:变量值中的空格稍后用作参数

标签 bash

在编写 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"

我希望这对那些寻求类似解决方案的人有用。

最佳答案

你会想要阅读 entry 050BASH FAQ :

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.

...

  1. 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/

相关文章:

arrays - 在 Bash 中获取关联数组( double )部分的长度

python - 我如何在 linux 中拆分 "who -m"命令的输出?

linux - 用于 sed 替换的转义文件名

bash - 如何用行号替换文本文件中的整行

Bash 脚本 "Command Not Found Error"

bash - 如何逐行读取文件并用 cat 执行每一行

Bash 脚本 : Illegal alias names

linux - 在主目录中的点文件夹周围加上引号会破坏 bash 命令

bash - 如何检索给定相对路径的绝对路径

bash - $GEM_PATH 通常设置在哪里?