Yola
Yola

Reputation: 19033

redirecting to file from var

#! /bin/bash
if [ $1 ]; then
  redirect="<"$1
else
  redirect="<&0"
fi
mysql --host=a.b --port=3306 --user=me --password='!' -D DCVBase2 $redirect

wanna redirect from either file or stdin. May be use some quatation around $redirect?

Upvotes: 2

Views: 166

Answers (3)

je4d
je4d

Reputation: 7838

You can't put the "<..." in a variable, but you can put the parameter to it in a variable

Also, redirecting stdin from /dev/fd/0 is a no-op, because /dev/fd/0 is bash's stdin, which is what mysql would inherit by default.

so you can make this work by falling back to taking stdin from /dev/fd/0, which looks similar to James_R_Ferguson's answer, except that it uses /dev/fd/0 because using /dev/tty makes an assumption that bash's stdin is an actual terminal.

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

Upvotes: 1

themel
themel

Reputation: 8895

Not possible in standard bash because the redirects are processed before variable expansion (though I can't seem to find a reference for that, so you'll have to believe my empirical findings).

You can work around that using the eval command:

$ redirect=">foo"
$ ls $redirect
ls: cannot access >foo: No such file or directory
$ eval ls $redirect

Beware that this opens a can of worms regarding substitution, quoting and so, so you have to be careful to escape everything you do not want interpreted BEFORE the eval (the ! in your command is likely going to be a problem, for example).

$ foo=\$bar
$ bar=baz
$ echo $foo
$bar
$ eval echo $foo
baz

Upvotes: 1

JRFerguson
JRFerguson

Reputation: 7516

Something like this will work:

#!/bin/bash
if [ "$1" ]; then
    redirect="$1"
else
    redirect="/dev/tty"
fi
while read LINE
do
    echo ${LINE}
done < ${redirect}

Upvotes: 2

Related Questions