Reputation: 4888
I have the following situation:
/usr/local/bin/rsnapshot.period
/etc/cron.[period]/
directories, like /etc/cron.hourly/rsnapshot
I'd like to have the script look up the full path to the symlink, and pull out the [period] part, so I can feed it to rsnapshot.
I can do all the text hacking. The problem I'm having trouble with is getting the path to the calling symlink from within the bash script. $0
seems to point to /usr/local/bin/rsnapshot.period
Is there a better way to get this info?
Upvotes: 1
Views: 130
Reputation: 4888
Turns out my problem wasn't that $0 was incorrect - it was pointing to the right place. However, as I was trying to get the absolute path of it, I was using 'realpath' before it, which resolved symlinks.
Passing realpath the '-s' fixed it. Here's my test script and the output of it:
Script:
#!/bin/sh
echo \$0: $0
echo realpath -s \$0: $(realpath -s $0)
echo readlink -e: $(readlink -e $0)
Executed:
$0: ./rsnapshot
realpath -s $0: /etc/cron.hourly/rsnapshot
readlink -e: /usr/local/bin/rsnapshot.period
Upvotes: 0
Reputation: 799500
$0
seems to point to/usr/local/bin/rsnapshot.period
$0
is set by the calling program in its exec*()
call, as the first word of the arg
argument or the first element of the argv
argument. If you feel that the tool you're using is setting this value incorrectly then you should open a bug with the developer.
In the meantime, using a hardlink instead of a symlink will allow you to detect the script name properly, but will break if you aren't careful with the tool you use to edit the main script.
Upvotes: 1