Repeating Commands

Running the same command over and over again can be a pain in the shell. With a small amount of configuration, you can set up a repeat shell command that makes this a bit more convenient. To do this, open the file .bashrc in your home directory with your favorite text editor. Files that start with a dot are hidden when you run ls (unless you pass the -a flag) so you may not see the file at first.

Once you have .bashrc open, add the following code to the file:

repeat() {
    n=$1
    shift
    while [ $(( n -= 1 )) -ge 0 ]
    do
        "$@"
    done
}

This defines a new repeat function, which you can use as a command in bash. Before you can use this command you will have to start a new shell or run the command source ~/.bashrc.

Examples

$ repeat 3 pwd
/home/curtsinger
/home/curtsinger
/home/curtsinger