Change dir in a script

I am trying to put in good practices.

Like avoid typos so my scripts run o.k.

This is not working?

 SOURCE=/home/andy
 TARGET=/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/
 DOCS=/home/andy/Documents
 DATE=$(/bin/date "+%F")

cd $DOCS

Hello,

What is not working ?
if your problem is When you launch your bash script you want to change your current working directory interactively to cd $DOCS you need to launch your bash by sourcing it

source ./mybash.sh

When you launch a bash using ./mybash.sh your script is launched in a sub process not the current one.
You can have a return of what you are doing eg

SOURCE=/home/sysadmin
TARGET=/media/sysadmin/MAXTOR_SDB1/Ubuntu_Mate_18.04/
DOCS=/home/sysadmin/Documents
DATE=$(/bin/date "+%F")

cd $DOCS
echo $$ => print current bash PID in which your script is working
ls => will print contents of $DOCS

But your "calling" bash will remain in the current path and your "called" bash will follow your cd non interactively.
Making a ps ax | grep bash after your bash execution will show you that the PID of the "called" bash sub process printed by echo $$ does not exist anymore.

IMHO, as good practices try to always

  • quote ".." your paths (to avoid issue when getting paths with other tools as find ...) and containing white spaces.
  • write your bash variable inside ${} as ${myvariable} (to avoid trouble when you concatenate vars and personally it is much easier to read an debug).
  • write your bash variable inside quotes ".." when the data type is a string
    Personally In bash script I prefer to use pushd and popd to change directory.

is that your problem ?

My mistake.

It works within the script, but it is not global.

I thought when script finished, it would be in the “DOCS” directory.

Hello,

No problem :slight_smile:
If you really want that your “calling” bash ends in your target $DOCS path you need to source it.

Kr,