[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: What is the difference between a newline and a semi-colon?

From: Eric Blake
Subject: Re: What is the difference between a newline and a semi-colon?
Date: Fri, 30 May 2014 09:13:01 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.5.0

On 05/30/2014 09:01 AM, Bruce Korb wrote:
>     $ . xx ; cat xx ; proj ; pwd ; pwd -P
>     alias proj="cd ~/'google drive'/web"
>     bash: proj: command not found
>     /home/sciadmin/tmp
>     /home/sciadmin/tmp
>     $ . xx
>     $ cat xx ; proj ; pwd ; pwd -P
>     alias proj="cd ~/'google drive'/web"
>     /home/sciadmin/google drive/web
>     /home/sciadmin/foo bar/web
> Clearly, there is a behavioral difference.  Is this a bug or feature?

Feature (albeit a warty one), and POSIX compliant (other shells have the
same behavior).  The man page documents that aliases are expanded at
PARSE time, but the shell has to parse the entire command line before
executing any of it.  Therefore, an alias cannot be used until AFTER the
line that defines it is completely executed, and the shell resumes
parsing new lines.

In your first example, the parser has already consumed text up to 'pwd
-P' prior to sourcing 'xx'; which means the alias defined in xx does NOT
affect the rest of that line.  In your second example, separating the
alias definition from the use of the 'proj' alias allows the parser to
expand 'proj'.  Want more fun? Try:

$ {

and that will also fail, because by surrounding your script in {}, the
parser now has to read to a trailing }.  It is NOT the presence of
newline vs. semicolon at play, but rather the rules on how far the
parser has to read to reach the end of the current command(s).

'man bash' mentions this under BUGS:

       Aliases are confusing in some uses.

There are VERY FEW REASONS to ever use an alias.  Shell functions are
more powerful, and behave more intuitively (they effect shell state at
execution, not parse).

(I've seen ONE case where an alias can do things that a function cannot:
writing an alias for 'find' that temporarily inhibits globbing on the
arguments for JUST the find command - that has to be done via an alias,
because it depends on affecting the parse, and a function call is too
late.  But in every other case, I have been able to rewrite an alias
into a function with no difficulties)

Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature

reply via email to

[Prev in Thread] Current Thread [Next in Thread]