diff --git a/pkgs/stdenv/generic/setup.sh b/pkgs/stdenv/generic/setup.sh
index 036eb81bb6966..de22e64691cf9 100644
--- a/pkgs/stdenv/generic/setup.sh
+++ b/pkgs/stdenv/generic/setup.sh
@@ -688,6 +688,28 @@ patchELF() {
 }
 
 
+patchShebangs() {
+    # Rewrite all script interpreter file names (`#! /path') under the
+    # specified  directory tree to paths found in $PATH.  E.g.,
+    # /bin/sh will be rewritten to /nix/store/<hash>-some-bash/bin/sh.
+    # Interpreters that are already in the store are left untouched.
+    header "patching script interpreter paths"
+    local dir="$1"
+    local f
+    for f in $(find "$dir" -type f -perm +0100); do
+        local oldPath=$(sed -ne '1 s,^#![ ]*\([^ ]*\).*$,\1,p' "$f")
+        if test -n "$oldPath" -a "${oldPath:0:${#NIX_STORE}}" != "$NIX_STORE"; then
+            local newPath=$(type -P $(basename $oldPath) || true)
+            if test -n "$newPath" -a "$newPath" != "$oldPath"; then
+                echo "$f: interpreter changed from $oldPath to $newPath"
+                sed -i "1 s,$oldPath,$newPath," "$f"
+            fi
+        fi
+    done
+    stopNest
+}
+
+
 installPhase() {
     if test -n "$installPhase"; then
         eval "$installPhase"
@@ -761,6 +783,10 @@ fixupPhase() {
         patchELF "$prefix"
     fi
 
+    if test -z "$dontPatchShebangs"; then
+        patchShebangs "$prefix"
+    fi
+
     if test -n "$propagatedBuildInputs"; then
         ensureDir "$out/nix-support"
         echo "$propagatedBuildInputs" > "$out/nix-support/propagated-build-inputs"