0

How do we expand a variable, ie. a '$' preceded name, to its value content on bash readline ?

  • 1
    That is a very peculiar use-case. Could you elaborate, where this would be useful? Maybe there are valid alternatives for what you are trying. Maybe you rather want to use envsubsts on the variable instead? – FelixJN Nov 02 '21 at 15:28

4 Answers4

4

Since you specifically mention readline, I think you want something so that this:

$ echo $foo

becomes:

$ echo bar

where bar is the value of $foo.

There is this readline expansion:

shell-expand-line (M-C-e)
Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions (see Shell Expansions).

M-C-e would typically be Esc Ctrl+e or Alt+Ctrl+e.

However, this also expands everything else, like command substitutions, arithmetic expansion, etc.. So this:

$ echo $SHELL $(date) $((11+22))

becomes:

$ echo /bin/zsh Wed 3 Nov 00:52:09 JST 2021 33
muru
  • 72,889
0

I don't know if I understood correctly your question but you can print a variable using echo.

0

Try this:

#!/bin/bash
DEFAULT_VALUE="default-value"
read -e -p $'\e[33mEnter variable name\e[0m: ' -i "$DEFAULT_VALUE" NEW_VAR
echo "New value for variable is: $NEW_VAR"
LincolnP
  • 526
  • Some additional information explaining the ANSI escape sequences and the read command would be useful since they're outside of the scope of the original question. – Brian Redbeard Nov 03 '21 at 19:15
0

I would not know of any way to expand a variable during read, but you may evaluate it afterwards without changing the result if the stored sting is not referring to a variable name:

read -e variable
$SHELL

echo $valiable $SHELL

eval echo $variable /bin/bash

echo $variable | envsubst /bin/bash

read -e n hello

echo $n hello

eval echo $n hello

echo $n | envsubst hello

Be aware of the dangers eval might have as it also runs any commands stored as variable. For security reasons, I'd thus strongly suggest sticking to envsubst.

FelixJN
  • 13,566