I am writing a bash script that must echo all of its arguments, which is surprisingly difficult to do.
The naive implementation looks like this:
#!/bin/bash
echo "$@"
However, that fails with input such as:
> ./script.sh -n -e -v -e -r
-v -e -r>
How can I make this more robust, such that the above results in:
> ./script.sh -n -e -v -e -r
-n -e -v -e -r
>
echo
command's behavior may be different between systems. The safest way is to use printf
:
printf '%s\n' "$*"
According to posix:
It is not possible to use
echo
portably across all POSIX systems unless both-n
(as the first argument) and escape sequences are omitted.The
printf
utility can be used portably to emulate any of the traditional behaviors of theecho
utility ...