Reputation: 1647
How to made bash to execute variable value. For example, we have this code, where variable value was set in single quotes(!).
#!/bin/bash
V_MY_PATH='$HOME'
echo "$V_MY_PATH"
ls $V_MY_PATH
The output is
$HOME
ls: $HOME: No such file or directory
How to made bash to translate shell variable insto its value if there is some.
I want to add some code after V_MY_PATH='$HOME' to make output like echo $HOME.
It's something simple, but i'm stuck. (NB: I know that with V_MY_PATH="$HOME", it works fine.)
EDIT PART: I just wanted to make it simple, but I feel that some details are needed.
I'm getting parameter from a file. This part works good. I don't want to rewite it. The problem is that when my V_MY_PATH contains a predefined variable (like $home) it's not treated like its value.
Upvotes: 6
Views: 55256
Reputation: 11
You can use single or double quotes, and in your case, none if you prefer.
You have nothing telling bash what the variable is equal to. Maybe something like this? (unless I misunderstand what you are trying to do)
======================================================================
#!/bin/bash
#########################
# VARIABLES #
#########################
V_MY_PATH=home
#########################
# SCRIPT #
#########################
echo "What is your home path?"
read $home
echo "Your home path is $V_MY_PATH"
ls $V_MY_PATH
Of course you could also just remove the variable at the top and use: echo "Your home path is $home"
Upvotes: 0
Reputation: 3619
use variable indirect reference so:
pete.mccabe@jackfrog$ p='HOME'
pete.mccabe@jackfrog$ echo $p
HOME
pete.mccabe@jackfrog$ ls ${p}
ls: cannot access HOME: No such file or directory
pete.mccabe@jackfrog$ ls ${!p}
bash libpng-1.2.44-1.el6 python-hwdata squid
...
pete.mccabe@jackfrog$
The ${!p} means take the value of $p and that value is the name of the variable who's contents I wish to reference
Upvotes: 8
Reputation: 33327
Remove the single quotes
V_MY_PATH='$HOME'
should be
V_MY_PATH=$HOME
you want to use $HOME
as a variable
you can't have variables in single quotes.
Complete script:
#!/bin/bash
V_MY_PATH=$HOME
echo "$V_MY_PATH"
ls "$V_MY_PATH" #; Add double quotes here in case you get weird filenames
Output:
/home/myuser
0
05430142.pdf
4
aiSearchFramework-7_10_2007-v0.1.rar
etc.
Upvotes: 11