0

I have a shell script:

TOPDIR=`pwd`
FOLDER=$($TOPDIR | sed 's/\//\_/g')
if [[ condition ]];then
  source ~/[$FOLDER]-build/build-env.sh
fi

the TOPDIR here is /home/uname/project, so the variable FOLDER is supposed to be _home_uname_project because sed is called to replace / with _.

But it goes wrong when executing, terminal tells that /home/uname/[]-build/build-env.sh: No such file or directory which, I guess, means that FOLDER is unexpected empty in the if-then statement. Can anybody help me with figuring this out?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
wangx1ng
  • 73
  • 1
  • 2
  • 10

1 Answers1

1

If you look at the output of just

$TOPDIR | sed 's/\//\_/g'

you'll realize that it's empty; it's trying to execute a command equal to the contents of $TOPDIR and pipe the output of that into sed, but there is no output in the first place.

You could do

pwd | sed 's\//_/g'

instead (no need to escape _), which would work.

Or, instead of using an external tool, you could use parameter expansion

topdir="$(pwd)"
topdir="${topdir//\//_}"

with the same result.

Notice that uppercase variable names are discouraged, as they're more likely to clash with existing, reserved names.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • It works with `pwd` instead of `$TOPDIR`! Thanks, especially for explaining me that `sed` needs a standard output to go with. – wangx1ng Feb 16 '16 at 06:56