0

I have a simple shell script that I am running via cron. I am using it to perform a scheduled git pull operation (yeah, I know there are probably better methods, but this is another team's repository and I just need to periodically read from it, so I'm opting for a quick and dirty solution).

Anyway, my script does something like this:

#!/usr/bin/bash

if /usr/bin/cd /opt/repos/other-teams-repo then echo "success!" else echo "fail :(" exit 1 fi

/usr/bin/pwd

if /usr/bin/git pull then echo "success on the pull" else echo "fail on the pull" exit 1 fi

From the command line, this works just fine. But when I run it via cron:

57 11 * * 1 /opt/myuser/shell/otheruser-repo-git-pull.sh > /opt/log/repo-pull.git.cronlog 2>&1

In my cronlog, I get this:

success!
/home/myuser
fatal: Not a git repository (or any parent up to mount point /home)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
fail on the pull

When I change /usr/bin/cd to cd and /usr/bin/pwd to pwd it works just fine.

I'm just curious if anyone has any insight as to why this might be?

ilkkachu
  • 138,973
Nick S
  • 103
  • 6
    What are you expecting /usr/bin/cd to do in this context? See for example What is the point of the cd external command? – steeldriver Jun 06 '23 at 15:39
  • 1
    "From the command line, this works just fine" – With /usr/bin/cd? – Kamil Maciorowski Jun 06 '23 at 15:53
  • As a note, when I call the script /opt/myuser/shell/otheruser-repo-git-pull.sh from the command line the script works as expect. When I call the script from cron, it failes. That is until I change /usr/bin/cd to cd. @steeldriver, I expect cd to change into the directory I pass it, so in the case change into /opt/repos/other-teams-repo. But it appears from your comment that /usr/bin/cd does NOT equal cd, hence the different behavior. – Nick S Jun 06 '23 at 16:56
  • @Kamil Maciorowski - it did work just fine using /usr/bin/cd! But it is probably because when I called the shell script, I happened to be in /opt/repos/other-teams-repo, so my pwd was where I was trying to change into. Retrying from /home/myuser, it fails from the command line with /usr/bin/cd just like it does in cron. steeldriver's comment led me to the distinction. I did not realize there was a different between /usr/bin/cd and cd. Thanks for the help folks. – Nick S Jun 06 '23 at 17:02

1 Answers1

0

The working directory is a property of the process, so an external binary like /usr/bin/cd can't change the shell's working directory. (It'll just change its own working directory and then exit.) You need the shell's builtin one, which you get when using just cd.

Yes, one might sensibly ask "What is the point of the cd external command?"

With pwd vs. /usr/bin/pwd there is no such issue, as the external pwd inherits the working directory of the shell, so it can print it same as the builtin one (as long as the path doesn't contain symlinks).

ilkkachu
  • 138,973