3

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!

1
  • 3
    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.) Jun 8, 2013 at 16:28

3 Answers 3

7

Use command substitution:

$ myvar=$(pwd)
$ echo $myvar
/etc
$ echo $(pwd)
/etc
1
  • Thanks, @Nykakin! I will make it accepted asnwer very soon! Jun 8, 2013 at 11:32
3

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.

0

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 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .