Search code examples
bashaliasrepeatls

Using asterisk in bash ls alias


In ~/.bash_aliases I want to create an alias for repeat word that will repeat given command n times.

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

I want to use repeat to list updated files in a directory so I made following function (WAIT,CLEAR,LIST):

wcls() {
    m=$1
    shift
    clear
    date
    ls -l "$@"
    sleep $m
}

I have a folder where are my_file1 and my_file2. If I run the script :

repeat 500 wcls 2 my_file*

i get

my_file1 ...
my_file2 ...

and in the mean time I change my_file2 to my_file3 the script wont update the contents showing

my_file1 ...
my_file2 no such file or directory

what should I do for my functions to correctly handle asterisks?


Solution

  • The problem here is that your asterisks are being expanded by the interactive shell. When you execute the alias, you feed it a list of files, not a filespec with an asterisk.

    I don't think there's an easy way around this, other than by escaping your asterisks and letting the alias do the expansion. Which is a bad idea, because then filenames with funny characters could affect what's being executed merely by their existence.