#! /bin/bash
if [ $1 ]; then
redirect="<"$1
else
redirect="<&0"
fi
mysql --host=a.b --port=3306 --user=me --password='!' -D DCVBase2 $redirect
想要从文件或stdin中重定向。可能会使用$ redirect的一些quatation?重定向到变量的文件
#! /bin/bash
if [ $1 ]; then
redirect="<"$1
else
redirect="<&0"
fi
mysql --host=a.b --port=3306 --user=me --password='!' -D DCVBase2 $redirect
想要从文件或stdin中重定向。可能会使用$ redirect的一些quatation?重定向到变量的文件
你不能把“< ......”在一个变量,但你可以把参数给它一个变量
此外,从标准输入重定向的/ dev/FD/0因为/ dev/fd/0是bash的stdin,这是默认情况下mysql会继承的东西。
所以你可以通过回退到从/ dev/fd/0开始,这看起来类似于James_R_Ferguson的答案,除了它使用/ dev/fd/0因为使用/ dev/tty做出了一个假设该bash的标准输入是一个实际的终端。
#! /bin/bash
if [ -n "$1" ]; then # note, I changed this to test for non-empty
redirect="$1"
else
redirect="/dev/fd/0"
fi3
mysql --host=a.b --port=3306 --user=me --password='!' -D DCVBase2 < "$redirect"
恐怕我没有足够的声望将它作为评论,所以这将不得不做。
像这样将工作:
#!/bin/bash
if [ "$1" ]; then
redirect="$1"
else
redirect="/dev/tty"
fi
while read LINE
do
echo ${LINE}
done < ${redirect}
在标准的bash不可能的,因为重定向变量扩展前处理(虽然我似乎无法找到一个参考,所以你将不得不相信我的实证结果)。
可以解决,使用eval命令:
$ redirect=">foo"
$ ls $redirect
ls: cannot access >foo: No such file or directory
$ eval ls $redirect
要注意的是这将打开关于替代一罐蠕虫,报价等等,所以你必须要小心,逃避一切你不想解释在评估之前(例如,你的命令中的!可能会成为一个问题)。
$ foo=\$bar
$ bar=baz
$ echo $foo
$bar
$ eval echo $foo
baz