1

When i run the script:

#!/bin/bash
DRUPAL_ROOT=$(drush status root --format=list)
if [ -z $DRUPAL_ROOT ]
then
  echo -e "Not exists Drupal core"
else
  echo $DRUPAL_ROOT
  cd $DRUPAL_ROOT
fi

Output:

# /right/drupal/root

But no change to path

If i run commands in terminal:

# DRUPAL_ROOT=$(drush status root --format=list)
# cd $DRUPAL_ROOT

Change OK

Any idea? Thanks.

marked as duplicate by Jeff Schaller, peterh says reinstate Monica, Stephen Rauch, Gilles 'SO- stop being evil' bash Dec 11 '17 at 20:37

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • More directly: unix.stackexchange.com/q/27139/117549 – Jeff Schaller Dec 11 '17 at 19:10
  • 1
    The script will cd into the directory, and then terminate, leaving you in the shell (and working directory) in which you invoked the script, not the script's final working dorectory. This can be shown by adding a pwd line after the cd command. – DopeGhoti Dec 11 '17 at 19:10
2

As mentioned in the comments, scripts are executed in subshells, so it is for that reason why the directory does not change. You can source the script with . or source, or create a function for this:

drup_cd() {
   DRUPAL_ROOT=$(drush status root --format=list)
   if [[ ! $DRUPAL_ROOT ]]; then
     echo -e "Not exists Drupal core"
   else
     echo "$DRUPAL_ROOT"
     cd "$DRUPAL_ROOT"
   fi
}

You can add it to your .bashrc, for example. Also note that using unquoted variables inside [ ] is prone to errors.

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