Is there a way to make a bash script which scans a directory dir0 for folders, such that for all folders dir1 which are found in dir0 a command dir1-command is created with the following definition:

dir1-command() {
 cd dir0/dir1
 echo "inside dir0/dir1"
 cd -

EDIT: The specific problem I'm trying to solve is this: I have a folder called scripts which has subfolders like scripts/haskell_script1 and scripts/haskell_script2. The way to launch, say, scripts/haskell_script1 is as follows:

haskell_script1() {
 cd scripts/haskell_script1
 stack exec haskell_script1 -- $@
 cd -

And so what I'd like to do is, every time ~/.bashrc is sourced, scan my scripts folder and generate a bunch of commands of form haskell_scriptX to save me time. That way I don't have to manually create a command for every haskell project/folder folder that I create.

  • What is the issue that you're trying to solve by this? – Kusalananda Jun 7 '17 at 12:01
  • @Kusalananda: I provided more detail in my question above. – George Jun 7 '17 at 12:27
  • 1
    Wouldn't it be easier to make a function, run_haskel, that takes an argument and executes ( cd scripts/haskel_$arg && stack exec haskell_$arg ) ? – Kusalananda Jun 7 '17 at 12:30

Add this to your .bashrc:

for script in scripts/haskell_script*
  # strip off the leading "scripts/" portion
  eval "function ${script} { 
    cd scripts/${script}
    stack exec ${script} -- \$@
    cd -

You have to be careful about anything inside that definition that might get prematurely evaluated, which is why I escaped the $ in $@.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.