Skip to content

Instantly share code, notes, and snippets.

@3noch
Last active May 19, 2022 09:00
Show Gist options
  • Save 3noch/cb7c276c0b8d3e9d6f403c9a051fbf5c to your computer and use it in GitHub Desktop.
Save 3noch/cb7c276c0b8d3e9d6f403c9a051fbf5c to your computer and use it in GitHub Desktop.
Command-line wrapper to put commands within a nix-shell using the nearest parent shell.nix file.
#!/usr/bin/env bash
# based on discussion: https://github.com/atom-haskell/haskell-ghc-mod/issues/160
origdir=$PWD
# Source nix env because this script is intended to be
# used by editors, e.g. Atom which doesn't source .bashrc,
# and we need NIX_PATH to be set correctly.
source ~/.nix-profile/etc/profile.d/nix.sh
# Walk up the FS hierarchy until we find a shell.nix
while [ "$PWD" != "/" ] && [ ! -f shell.nix ]; do
cd ..
echo "$PWD"
done
# If we didn't find a shell.nix, give up.
if [ "$PWD" = "/" ]; then
(>&2 echo "No shell.nix found")
exit 1
fi
nixshelldir=$PWD
# Arg list trick:
# https://stackoverflow.com/questions/3104209
ARGS=$(printf "%q"" " "$@")
# get a filename this is executed with
execf="$(basename $0)"
mydir="$(dirname $0)"
# Remove this script's basedir from PATH
PATH=":$PATH:"
PATH=${PATH//:$mydir:/:}
PATH=${PATH#:}
PATH=${PATH%:}
# Just in case
export PATH
# Run $execf inside nix-shell
cd $origdir
nix-shell $nixshelldir/shell.nix --run "$execf $ARGS"
@3noch
Copy link
Author

3noch commented Nov 10, 2016

To use, just create symlinks from your tools to this script. E.g. ln -s nix-wrap ~/bin/cabal to get a cabal that runs inside of a nix-shell. Of course, your relevant shell.nix must pull in cabal-install for this to actually work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment