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.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@
$() – the command substitution. ${} – the parameter substitution/variable expansion.
You can go back to the parent directory of any current directory by using the command cd .. , as the full path of the current working directory is understood by Bash . You can also go back to your home directory (e.g. /users/jpalomino ) at any time using the command cd ~ (the character known as the tilde).
• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With