#! /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