Running a Simple Script from the GRASS Shell

Posted on Updated on

1. The simple GRASS script below will generate the least cost route from point A to point B given just two constraints, elevation and slope. The script can be easily expanded to include more constraints.

2.  To Run the script, copy it and save it as a text file with a name that ends in .sh, e.g. At the GRASS monitor, type “sh” plus the path to the script:

GRASS 7.0.0 (nc_spm_08):~ > sh /Users/xxx/Desktop/


# Author: gisstuff
# Purpose: Script to calculate Least Cost Route Between two points based on slope.
# Data Requirement:  A single Digital Elevation Model

#Start monitor
d.mon start=wx2

#Clear monitor

#Generate slope from Wayne County DEM
r.slope.aspect elevation=wayne slope=slope format=percent –overwrite

#Reclassify slope map
r.reclass –overwrite input=slope output=slope_reclass rules=/Users/xxx/Desktop/reclass.txt title=”Reclass Slope”

#Reclassify slope map
r.reclass –overwrite input=wayne output=wayne_reclass rules=/Users/xxx/Desktop/reclass_elevation.txt title=”Reclass_Elevation”

#Sum the two cost estimates
r.mapcalc “total_surface = slope_reclass + wayne_reclass”

#Get the total accumulated cost surface
r.cost input=total_surface output=costDist start_points=start stop_points=end –overwrite

#Display Total Cost Surface
d.rast costDist

#Generate the least cost path raster
r.drain input=costDist output=slope_path2  –overwrite start_points=start,end

#Convert the least cost raster to vector -s input=slope_path2 output=slope_path2 type=line –overwrite

#Display the least cost vector
d.vect slope_path2

exit 0


The text file, reclass.txt, contains instructions for reclassifying the slope raster. The content of that file is shown below. Copy it and save it as “reclass.txt”.

#Reclass Rules Slope
0 thru 2 = 2
2 thru 5 = 4
5 thru 10 = 8
10 thru 20 = 16
20 thru 30 = 32
30 thru 40 = 8
40 thru 50 = 128
50 thru 60 = 256
60 thru 100 = 512


One thought on “Running a Simple Script from the GRASS Shell

    gisstuff responded:
    May 11, 2015 at 9:35 pm

    Reblogged this on Applied GIS.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s