Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use bash $HOME in shell script

Tags:

bash

shell

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.

like image 480
idobr Avatar asked Jan 28 '13 11:01

idobr


People also ask

What is $_ in shell script?

$_ (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. $@

What is $() in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.

How do I get to the home directory in bash?

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).

What is $@ and $* in shell script?

• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.


2 Answers

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.

like image 140
user000001 Avatar answered Oct 08 '22 20:10

user000001


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

like image 20
peteches Avatar answered Oct 08 '22 20:10

peteches