Monday, May 16, 2011

get path in bash

When running a bash shell you might want to find files and directories relative to the path of the script. The use of 'pwd' in this case can lead to problems if the script has been run from another directory. What you need is the absolute path of the script being executed. Here's an example of how to do it. This works on most Linuxes but unfortunately is not supported on Mac OSX.

#!/bin/bash
# A simple test script to demonstrate how to find the
# "absolute path" at which a script is running. Used
# to avoid some of the pitfals of using 'pwd' or hard-
# coded paths when running scripts from cron or another
# directory.
#
# Try it out:
# run the script from the current directory, then
# cd.. and run it again (using the file path).
#
# You can see that CURDIR changes depending on where
# you run the script from, but ABSDIR stays the same.
CURDIR=`/bin/pwd`
BASEDIR=$(dirname $0)
ABSPATH=$(readlink -f $0)
ABSDIR=$(dirname $ABSPATH)
echo "CURDIR is $CURDIR"
echo "BASEDIR is $BASEDIR"
echo "ABSPATH is $ABSPATH"
echo "ABSDIR is $ABSDIR"
view raw bashpath.sh hosted with ❤ by GitHub

Productivity and Note-taking

I told a friend of mine that I wasn't really happy with the amount of time that gets taken up by Slack and "communication and sched...