Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely echo all arguments of a script? [duplicate]

Tags:

bash

echo

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
> 
like image 540
zennehoy Avatar asked Oct 27 '25 14:10

zennehoy


1 Answers

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 the echo utility ...

like image 98
pynexj Avatar answered Oct 30 '25 03:10

pynexj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!