Bash tip

Lennart Sorensen lsorense-1wCw9BSqJbv44Nm34jS7GywD8/FfD2ys at public.gmane.org
Sun Mar 28 00:19:29 UTC 2004


On Sat, Mar 27, 2004 at 05:59:15PM -0500, James Knott wrote:
> I have discovered a simple method for conditionally running a command, 
> depending on if a file exists.
> 
> When you want to run a command, when a file exists, the usual form has 
> been something along the lines of:
> 
> if [ -x aaa ]; then
>   bbb
> fi
> 
> However, I've noticed that you can also use
> 
> ls aaa && bbb
> 
> The "&&" in the command says to run the second part of the command, only 
> if the first part runs successfully.  You could also use "||", if you 
> want to run the second part,  only if the first part fails.  Since ls 
> uses std out, for success and std err for failure, you can also control 
> the output to show one or the other.  For example, if you want to show 
> the files that were found, you could use:
> 
> ls aaa 2>/dev/null && bbb
> 
> There are many variations on the above which may be useful.

But remember that running ls is an external command, while test (and
hence '[') is often a shell builtin so you save a fork, exec, etc call
which could make quite a difference in performance of the script.  test
also has the ability to easily check many different stats about a given
parameter which ls would need help from grep to determine (yet another
process to launch).

I will stick to using test for what it is best at, and conditional
execution for things like: 

while ! (apt-get update && apt-get -y --download-only dist-upgrade); do
: ; done && poff

Lennart Sorensen

Lennart Sorensen
--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list