To feed input to an interactive script, I've been using a here-string:

script <<< $'1 2\n3 4\n5 6\nq'

This effectively enters

1 2
3 4
5 6

into the script. But how can I replace one of these with a variable?

script <<< $'$var 2\n3 4\n...'

does not work...

  • have you tried double quote (") ? – Archemar May 27 '16 at 8:29
  • I tried, and it does not seem to work. – snurden May 27 '16 at 8:54
  • just in case echo "$var 2\n3 4\n..." | script ? – Archemar May 27 '16 at 8:56
  • Not working either, but echo "1 2\n3 4\n..." | script is also not working properly, so... – snurden May 27 '16 at 8:58
  • man echo (or man bash and search for echo) → echo -e – roaima May 27 '16 at 9:24

That's not the here string, it's ANSI-C quoting:

Words of the form $'string' are treated specially. ... The expanded result is single-quoted, as if the dollar sign had not been present.

So what you've got is a single-quoted string to the right of <<<. That string gets taken as the here string, with no further processing.

There's no need to use only a single set of quotes around the whole word, however. You can use several quoted parts (or unquoted single words) joined together:

script <<< "$var 2"$'\n'"3 4"$'\n'"5 6"$'\n'q

will do what you wanted.

Alternatively, you could backslash-escape the spaces, rather than quoting "1 2".

You could also use echo -e with a regular pipe:

echo -e "$var 2\n3 4\n5 6\nq" | script

or printf:

printf '%s 2\n3 4\nq' "$var" | script

-e is necessary to enable escape processing in echo's arguments. printf does those by default, but it has its own interpolation system (printf "$var 2\n3 4\nq" will also work, but is problematic if $var might contain escape characters).


The $'...' ANSI-C quoting results in a "single-quoted" string.
Inside a single quoted string variables are not expanded:

$ var=13

$ echo 'test $var'
test $var

You need to take the variable out of such structure. The easiest way IMO is:

$  printf -v val '%s 2\n3 4\n5 6\nq' "$var"
13 2
3 4
5 6

The format to printf is very similar to what you had before, and the %s is replaced by the value of the variable. To get the result in a variable, we can use the capacity of bash printf of setting a variable:

$ printf -v val '%s 2\n3 4\n5 6\nq' "$var"
$ script <<< "$val"

All in one line:

$ printf -v val '%s 2\n3 4\n5 6\nq' "$var"; script <<< "$val"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.