Search code examples
bashpwd

How to check directory in which script will execute


I'm having problem with storing current path and comparing it with the one user entered. At the moment I have

cd $path
checkpath="$(pwd)"
if [ "$checkpath" == "$path" ]; then
chown -Rv $user *

and the $path is entered by user. Script fails at the above point each time and I can't figure out why. I just need a way to check that the chown part will really execute under the path that user entered.

edit: $path contains path that user entered while checkpath should contain output generated by pwd. So on short, yes, I'm trying to make sure that cd command worked and that chown will be executed in the directory which used wrote when he was asked for it.


Solution

  • cd "$path" && chown -Rv "$user" *
    

    This only executes chown if the cd command succeeds. Other ways of writing the same thing:

    if cd "$path"; then
        chown -Rv "$user" *
    fi
    

    or

    cd "$path" || exit
    chown -Rv "$user" *
    

    or

    #!/bin/bash -e
    cd "$path"
    chown -Rv "$user" *
    

    The last sets the shell's -e flag, which causes it to exit immediately if any command fails rather than continuing on.