5

Is it possible to run a command multiple times with different parameters?

Something like:

sudo apt-get install asd && install qwe && remove ert && autoremove && autoclean
fedorqui
  • 275,237
  • 103
  • 548
  • 598
canavaroski90
  • 97
  • 1
  • 2
  • 7

5 Answers5

11

Use either a for loop:

for cmd in "install asd" "install qwe" "remove ert" "autoremove" "autoclean"; do sudo apt-get $cmd; done

or xargs:

echo -e "install asd\ninstall qwe\nremove ert\nautoremove\nautoclean" | xargs -I "#" sudo apt-get "#"
Vadim Landa
  • 2,784
  • 5
  • 23
  • 33
7

If you are working from the command line, you can probably use the following: once you ran command parameter1, repeat command with parameter2 instead typing:

^paramater1^parameter2

Example

I have two files: a1 and a2. Let's ls -l the first:

$ ls -l a1
-rw-r--r-- 1 me me 21 Apr 21 16:43 a1

Now let's do the same for a2:

$ ^a1^a2
ls -l a2                # bash indicates what is the command being executed
-rw-r--r-- 1 me me 13 Apr 21 16:43 a2

You can find more tricks like this in What is your single most favorite command-line trick using Bash?.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
4

This loops a set of parameters and applies them to the same command. There is no error checking, unlike in your example which will fail if one of the earlier commands fails

for param in asd qwe ert; do install $param; done
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
0

No. Unfortunately, the shell cannot read your mind.

You could do something like this:

alias sag="sudo apt-get"
sag install asd qwe && sag remove ert && sag autoremove && sag autoclean

Although I'm not convinced that you really want && there; you might be just as happy with ;

rici
  • 234,347
  • 28
  • 237
  • 341
0

In the most general case, if you have a set or parameters you want to loop over, perhaps try

for first in one "two, with cinnamon" three; do
  for second in red yellow "odd color between brown and gray"; do
    for third in 0.1 0.5 1.0 2.0; do
        frobnicate --number "$first" --color "$second" --limit "$third"
    done
  done
done

or perhaps

while read -r first second third; do
  frobnicate --number "$first" --color "$second" --limit "$third"
done <<____EOF
  sixty-five   mauve    0.1
  sixty-five   crimson  0.1
  fifty-eleven lilac    0.2
  fifty-eleven lilac    0.5
  17           black    1.0
  42           black    1.0
____EOF
tripleee
  • 175,061
  • 34
  • 275
  • 318