You are not logged in.

#1 2019-05-04 17:38:11

r00t
Member
From: Canada
Registered: 2019-04-18
Posts: 43

echo vs printf

So i see that your useing echo, is there a reason for echo rather than printf ?

other than saving a bit of typing in some cases ?

maybe the real question should be, if i use printf rather than echo in scripts, would it still be useul [ here in this project [bunsen labs] ], or should i follow the echo format ?


The distance between insanity, or genus is measured only by success .

Offline

#2 2019-05-04 18:37:06

damo
....moderator....
Registered: 2015-08-20
Posts: 5,057

Re: echo vs printf

Google "echo or printf" and decide yourself what is appropriate for your use case.


Be Excellent to Each Other...

FORUM RULES and posting guidelines «» Help page for forum post formatting
Artwork on DeviantArt  «» BunsenLabs on DeviantArt

Offline

#3 2019-05-04 19:36:29

twoion
ほやほや
Registered: 2015-08-10
Posts: 2,482

Re: echo vs printf

echo the shell builtin shouldn't be used unless you control or sanitized the contents of the string that's used as its first argument (because if the string is -e, escape sequences that manipulate the terminal (emulator may be injected) in the second string).

printf the shell builtin allows printf-style formatting and more control. Here, you should sanitize or control at least the first argument, the format spec.

In general, sanitize your inputs and then use the best tool for doing the job. printf is closer to C printf(3)-style output formatting; echo is closer to just putting a line on the screen (PRINT in basic, or so) but as explained not without caveats.

OUT=-n
echo "$OUT" # boohoo, probably not what you wanted
printf "%s\n" "$OUT" # but this works as intended

A silent kite against the blue, blue sky

Offline

#4 2019-05-04 19:49:22

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 1,816
Website

Re: echo vs printf

I keep finding interesting ways to use printf, like

    # round float
    a=3.123456
    printf "%.2f\n" "a"         
    3.12
    printf "%.4f\n" "a"
    3.1235

    # type protection ?
    a="1"
    printf "%d\n" "a"
    1
    a="b"
    printf "%d\n" "a"
    0

Last edited by brontosaurusrex (2019-05-04 19:50:21)

Offline

#5 2019-05-05 09:00:46

ohnonot
...again
Registered: 2015-09-29
Posts: 3,907
Website

Re: echo vs printf

printf is pretty versatile. can even print to a variable. i think echo exists for being quick & straightforward to use.
but real luddites use cat:

cat <<EOF
-n
EOF

big_smile

Offline

#6 2019-05-06 14:30:44

r00t
Member
From: Canada
Registered: 2019-04-18
Posts: 43

Re: echo vs printf

ok clearly i need to read a bit more, the only real differance i was sure about, was that printf was builtin ...


The distance between insanity, or genus is measured only by success .

Offline

Board footer

Powered by FluxBB