unexpected result from sh script with `date`
Erik Trulsson
ertr1013 at student.uu.se
Fri Feb 2 14:06:46 UTC 2007
On Fri, Feb 02, 2007 at 01:48:31PM +0100, J65nko wrote:
> On 2/2/07, Tigger <tigger at lvlworld.com> wrote:
> >Hello, the following simply sh script is outputting unexpected results.
> >Any idea why?
> >
> >--script--
> >
> >#!/bin/sh
> >
> >started=`date`
> >
> >echo "Started at: $started"
> >echo "Finished : "`date`
> >exit
> >
> >--output--
> >
> >Started at: Fri Feb 2 22:13:51 EST 2007
> >Finished : Fri Feb 2 22:13:51 EST 2007
> >
> >--problem--
> >
> >Between 'Feb' and '2', there is two spaces on the 'Started at' line,
> >however the 'Finished' one only has 1 space.
> >
> >I know this sounds picky, but I was not expecting this at all.
> >
> >uname -a
> >FreeBSD piglet 6.2-STABLE FreeBSD 6.2-STABLE #0: Fri Jan 19 04:13:20 EST
> >2007 tigger at piglet:/usr/obj/usr/src/sys/PIGLET i386
>
> The same on OpenBSD here (ksh)
> OpenBSD 4.0-current (GENERIC) #1194: Thu Nov 2 16:32:12 MST 2006
> deraadt at i386.openbsd.org:/usr/src/sys/arch/i386/compile/GENERIC
>
> It seems to depend whether the command substitution is within the
> quote-delimited string, for 'echo' or outside that string, in other
> words on its own.
> ------- script----------
> #!/bin/sh
>
> started=$(date)
>
> echo "\$started within \" delimited string for echo"
> echo "Started at: $started"
> echo "Command substitution \$(date) within \" delimited string for echo"
> echo "Finished : $(date)"
> echo "Command substitution \$(date) outside \" delimited string for echo"
> echo "Finished : "$(date)
> echo "Command substitution \`date\` outside \" delimited string for echo"
> echo "Finished : "$(date)
> -----------------------------------
> Output:
> -------------------
> $started within " delimited string for echo
> Started at: Fri Feb 2 13:46:07 CET 2007
> Command substitution $(date) within " delimited string for echo
> Finished : Fri Feb 2 13:46:07 CET 2007
> Command substitution $(date) outside " delimited string for echo
> Finished : Fri Feb 2 13:46:07 CET 2007
> Command substitution `date` outside " delimited string for echo
> Finished : Fri Feb 2 13:46:07 CET 2007
> ---------------------------------------
> Embedded inside the string there are two spaces between Feb and the 2,
> as "stand-alone" there is only one space.
>
> Strange indeed ;)
Not strange at all if think about how 'echo' works and how the arguments are
passed to it.
If you do a
echo `date`
then echo will be passed 6 arguments ('Fri' 'Feb' '2' '13:46:07' 'CET' '2007')
and print them with a single space between each of them.
If you do a
echo "`date`"
then echo will be passed only a single argument ('Fri Feb 2 13:46:07 CET 2007')
which will be printed unmodified.
As another example compare the outputs of
echo a b c
and
echo "a b c"
--
<Insert your favourite quote here.>
Erik Trulsson
ertr1013 at student.uu.se
More information about the freebsd-questions
mailing list