Skip to content

Instantly share code, notes, and snippets.

@alber70g
Last active October 26, 2021 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alber70g/fc3e835eca542e1095a494f4b5aaf5f7 to your computer and use it in GitHub Desktop.
Save alber70g/fc3e835eca542e1095a494f4b5aaf5f7 to your computer and use it in GitHub Desktop.
Wrap command and execute it in a target directory

Execute command in target directory

This will allow you to create aliases that take a command, and execute it in a target directory when that is available

Usage:

  1. download execute-in.sh and place it in your home dir

  2. make this file executable chmod +x execute-in.sh

  3. create an alias

    alias `command`="~/execute-in.sh `target` `command`"
    alias yarn="~/execute-in.sh app/javascript yarn"
#!/usr/bin/env bash
# usage:
# 1. make this file executable `chmod +x execute-in.sh`
# 2. create an alias
# alias `command`="~/execute-in.sh `target` `command`"
# example: alias yarn="~/execute-in.sh app/javascript yarn"
cwd=$(pwd)
target="$1"
command="$2"
if [ $(pwd | grep $target 2>&1) ]; then
# in $target
echo "in $target"
echo "> $target ${@:3}"
$command "${@:3}"
elif [ -d "$target" ]; then
# not in $target but $target exists
echo "> cd $target"
cd $target
echo "> $command ${@:3}"
$command "${@:3}"
cd $cwd
else
# $target doesn't exist
echo "$command $1 $2 doesn't exists, continuing"
echo "> $command ${@:3}"
$command "${@:3}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment