• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 167
  • Last Modified:

Detecting dir change in script

How would I verify if I had a sucessful dir change in a script? For example if in a script I have:

cd $newDir

or cd docs

how would I verify that the cd happened?????/

0
894359
Asked:
894359
  • 3
  • 2
  • 2
1 Solution
 
biraCommented:
hi
   Use pwd in your script to show current directory, as below:

    newDir=/tmp
    cd $newDir
    pwd


0
 
biraCommented:
OOOPPPsss

   You should also call the script using a dot before the script name:

     . yourscript
0
 
894359Author Commented:
Not following you! I thoght about saving path before change and then comparing!

currPathname=`pwd`
    cd $branch
     
     if [ `pwd` != "$currPathname$branch" ] ; then
      echo "Could not cd to the correct branch directory: $branch" >&2
      exit 2
    fi
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
biraCommented:
So what about this  ?


   newDir=/tmp
   cd $newDir
   if [ $? != 0 ] ; then
       echo "cd failed"
     exit
   fi
      echo "cd OK" to `pwd`

 *** dont forget to place the dot when firing the script
     in order to use the parent shell:

             . yourscript
0
 
TintinCommented:
Short way is to do

cd /some/dir || exit $?

0
 
894359Author Commented:
Hi Tintin will this work ?

Short way is to do

cd /some/dir || exit 2 $? echo "something here!"

Also what does the $? do?
0
 
TintinCommented:

The $? variable contains the return code of the last command.

If the cd fails for whatever reason, the return code will be > 0.

If you want to do more than just an exit with the status, then use something like bira's solution (although, it should really use -ne instead of != for the comparision)

If you have lots of similar checks you can do something like:

#!/bin/sh

Error
{
  echo "$*" >&2
  exit 1
}

cd /some/dir || Error "cd failed"
[ -f /some/file ] || Error "/some/file does not exist"
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now