Home > Enterprise >  How to change content in variable based on pwd in bash?
How to change content in variable based on pwd in bash?

Time:06-05

I would like to do following:

  1. get all dependencies (dir names)
  2. get basename of current directory
  3. since current directory is not a dependency, get rid of it
  4. print them

what I have so far (from bashrc):

export dep=$({ tmp=$(ls /usr/local/lib/node_modules/); echo ${tmp//$(basename $(pwd))/}; })

The goal is it to have it in variable, not a function or alias becuase I want to use it later (such as for npm link $dep), which I would not be able if it was function.

But the current output DOES include the current directory. Was it invoked from the current dir, the current dir would not be included. So I guess the variable is not reexecuted to take into account it changed its dir (from where bashrc is, to where I am now).

So how to make it to NOT include the current dir?

CodePudding user response:

A variable is simply static text, the shell (or, let alone, the string itself) in no way keeps track of how its value was calculated; it's just a sequence of characters. If you need the value to change depending on external circumstances, you need to assign it again in those circumstances, or simply use a script or a function instead of a variable.

Here is a simple function which avoids trying to parse the output from ls:

getdep () {
    ( cd /usr/local/lib/node_modules
      printf '%s\n' * ) |
    grep -vFx "$(basename "$(pwd)")"
}

You would call it like

dep=$(getdep)

when you need to update dep, or simply use $(getdep) instead of $dep.

  • Related