Alan Stewart
Alan Stewart

Reputation: 93

In Ubuntu, how do I make an alias inside a bash for loop?

I have a script to help me with testing concurrency. I use screen to run a bunch of things at once. But within all that, I can't figure out how make an alias (or function?) using the for $i variable.

#!/bin/bash
# alias p='. ./p.sh'

# Run a bunch of apps in separate screens.

export NUM_MUS=3
for (( i = 1; i <= $NUM_MUS; ++i ))
do
   echo $i
   cd ~/mutest/mu$i
   screen -mS mu$i -h 10000 ./app

# How do I make an alias to let me easily access each screen?
# None of these work.
#
#   alias mu$i='screen -dr mu$i'
#   eval
#   function mu$i () { screen -dr mu$i }

   # ^AD to get out
done

# Have a way of killing them all.

function mustop ()
   {
   for (( i = 1; i <= $NUM_MUS; ++i ))
   do
      screen -r mu$i -X quit
   done
   screen -ls
   }

Please note that I am NOT asking about taking parameters. I don't want parameters ... unless there IS a way to make it work with parameters?

...

Okay, I can add this line, and it'll work "good enough"

function mu { screen -dr mu$1 }

But it still doesn't answer my question of using for loop variables to make a buncha aliases/functions. I'm not saying that's this is smartest way to do things, but if I did want to do this, how would I do it?

Upvotes: 0

Views: 335

Answers (1)

Barmar
Barmar

Reputation: 780889

Variables are expanded inside double quotes, not inside single quotes.

alias mu$i="screen -dr mu$i"

Also, make sure you run the script using source scriptname, so the aliases will be defined in your original shell, not just the shell executing the script.

Upvotes: 2

Related Questions