You should use a function. You could do something like this:
perms() { files=( * ); stat -c '%s - %n' "${@:-${files[@]}}"; }
which stores the contents of the current directory in an array files[]
and then prints "$@"
if populated or "${files[@]}"
otherwise. The problem with that is if there are no files in your directory than *
would be passed to stat
literally and fail complaining there's no file named *
and exit with a failure status, both of which I assume would be undesirable behavior, e.g. running in an empty directory:
$ perms() { files=( * ); stat -c '%s - %n' "${@:-${files[@]}}"; }
$ perms
stat: cannot stat '*': No such file or directory
$ echo $?
1
You could add shopt -s nullglob
to try to solve that problem but then stat would fail complaining about a null argument:
$ perms() { shopt -s nullglob; files=( * ); stat -c '%s - %n' "${@:-${files[@]}}"; }
$ perms
stat: cannot stat '': No such file or directory
$ echo $?
1
so that alone doesn't solve the problem (and you'd also need to set nullglob
back to it's previous value before leaving the function so that wouldn't be enough of a change anyway).
So, I'd recommend you do this instead:
$ perms() {
local files
if (( $# > 0 )); then
files=( "$@" )
else
local orig_nullglob=$(shopt -p nullglob)
shopt -s nullglob
files=( * )
$orig_nullglob
fi
if (( "${#files[@]}" > 0 )); then
stat -c '%s - %n' "${files[@]}"
fi
}
$ > foo
$ > bar
$ perms foo
0 - foo
$ perms
0 - bar
0 - foo
$ rm foo bar
$ perms
$ echo $?
0
and that will only exit with a failure exit status if one of the commands in the function fails or you pass it an argument for a file name that doesn't exit, which I assume would be desirable behavior:
$ perms nonsense
stat: cannot stat 'nonsense': No such file or directory
$ echo $?
1
The above assumes you're using bash
as you tagged. If you're actually using zsh
as you also tagged then idk what changes would be needed.