1

Can I use a for or while loop when I have similar pattern in the aliases that I put in my .bashrc file? For example, I have:

alias c0='ssh computer-1-0'
alias c1='ssh computer-1-1'
alias c2='ssh computer-1-2'
alias c3='ssh computer-1-3'
alias c4='ssh computer-1-4'

But I want to do something like

i=0
while [ i -le 4 ]
do
alias "c$i"="ssh computer-1-$i"
i=`expr $i + 1`
done 

which doesn't work unfortunately. I get an error message: -bash: [: i: integer expression expected.

Is there a way to achieve what I desire?

2

You were very close:

i=0
while [ $i -le 4 ]; do
  alias "c$i"="ssh computer-1-$i"
  i=`expr $i + 1`
done

Just add a $ character before i inside the while loop.

1
  • Now I relaized it was a stupid mistake and hence a bit silly question. I shall be careful before posting next time.
    – hbaromega
    May 19 '15 at 10:00
1

Your immediate problem is that i is just a one-character string. To access the value of the variable i, you need to use the syntax to access the value of a variable: "$i".

while [ "$i" -le 4 ]

(You can omit the double quotes here, but using them is a good habit to get into.)

Shells have basic arithmetic built in. The expr utility is a remnant from the old days when they didn't. You can write

i=0
while [ "$i" -le 4 ]
do
  alias "c$i=ssh computer-1-$i"
  i=$((i + 1))
done

Note that you don't need (and shouldn't use) a dollar inside the double parentheses. Inside an arithmetic expression, a variable name expands to the value of the variable.

Bash has a C-like for loop syntax. Since this is your bash startup file, there's no reason not to use bash-specific syntax.

for ((i = 0; i <= 4; i++)); do
  alias "c$i=ssh computer-1-$i"
done
1
  • I feel ashamed of doing such a stupid mistake. How can I forget $i? Anyway, your for-loop alternative is something that looks far simplified. Thanks a lot.
    – hbaromega
    May 19 '15 at 9:57

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.