You can use shift builtin to discard one or more positional parameters, but you should check the number of parameters first:
if [ "$#" > 1 ]; then
# Save first parameter value for using later
arg1=$1
shift
fi
Calling shift
without any argument meaning shift 1
.
Looping through all positional arguments:
for arg do
: do something with "$arg"
done
In your case, you don't need the loop at all, since when cat
can work with multiple files:
cat -- "$@"
Here's a test for calling shift
when there's no positional arguments:
$ for shell in /bin/*sh /opt/schily/bin/[jbo]sh; do
printf '[%s]\n' "$shell"
"$shell" -c 'shift'
done
Output:
[/bin/ash]
/bin/ash: 1: shift: can't shift that many
[/bin/bash]
[/bin/csh]
shift: No more words.
[/bin/dash]
/bin/dash: 1: shift: can't shift that many
[/bin/ksh]
/bin/ksh: shift: (null): bad number
[/bin/lksh]
/bin/lksh: shift: nothing to shift
[/bin/mksh]
/bin/mksh: shift: nothing to shift
[/bin/pdksh]
/bin/pdksh: shift: nothing to shift
[/bin/posh]
/bin/posh: shift: nothing to shift
[/bin/sh]
/bin/sh: 1: shift: can't shift that many
[/bin/tcsh]
shift: No more words.
[/bin/zsh]
zsh:shift:1: shift count must be <= $#
[/opt/schily/bin/bsh]
shift: cannot shift.
[/opt/schily/bin/jsh]
/opt/schily/bin/jsh: cannot shift
[/opt/schily/bin/osh]
/opt/schily/bin/osh: cannot shift
Well, bash
is silent with no positional arguments. Calling with placeholder in $0
:
"$shell" -c 'shift' _
made csh
variants and schily bsh
to be silent, too. In case of error, zsh
, csh
variants and schily bsh
won't quit the non-interactive script after reporting it.
"$@"
should always be quoted. Another side note, you can get the same functionality without thefor
loop:cat "$@"
.