Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I want to declare variable with pwd() function, which will give me the current path. I want to use pwd() function as ${pwd} variable, something like that. How I must write? Thanks!

share|improve this question
2  
Note that $PWD (all caps) is a special variable in Bash that is automatically set to the current directory path, always. (See "Shell Variables" in the bash(1) man page.) –  200_success Jun 8 '13 at 16:28

3 Answers 3

up vote 7 down vote accepted

Use command substitution:

$ myvar=$(pwd)
$ echo $myvar
/etc
$ echo $(pwd)
/etc
share|improve this answer
    
Thanks, @Nykakin! I will make it accepted asnwer very soon! –  Ziyaddin Sadigov Jun 8 '13 at 11:32

Providing functions as parameters is not intended and will soon get tricky or ugly. The only way I know is via the eval function. Nykakins approach isn't passing a function, but a value, as you can see in this comparing example:

#!/bin/bash
#
# Test providing a function as parameter
#
function f {
  param=$1
  echo "-----------------------"
  date +%T_%N
  sleep 0.3
  echo $param
  date +%T_%N
}

function e {
  param="$1"
  echo "-----------------------"
  date +%T_%N
  sleep 0.3
  eval $param
  date +%T_%N
}

f $(date +%T_%N) 
e "date +%T_%N"

The first style evaluates the function 'date' before passing it's result to the client function f, as you can see, because the second time is before the third:

-----------------------
14:00:12_983387321
14:00:12_980980238
14:00:13_287779378
-----------------------
14:00:13_290126185
14:00:13_594301594
14:00:13_596408013

The second block shows, that the passed over function is evaluated between the two date-calls in the e-function.

Maybe you hadn't that strict naming convention in mind, when asking for a function as variable, but I would say that this makes the difference between a function as variable and the result of a function as variable.

share|improve this answer

Bash doesn't implement it but otherwise what you are precisely asking for, i.e. use variables exactly as functions, is very simple to implement with ksh93 discipline functions, eg:

#!/bin/ksh93

function pwd.get
{
    .sh.value=$(pwd)
}

cd /var/tmp
echo $pwd
cd /tmp
echo $pwd

When executed, the previous script shows:

/var/tmp
/tmp 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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