[TriLUG] Basic bash shell scripting question

bp bpevans at bellsouth.net
Thu May 29 10:36:24 EDT 2003


Jeremy Portzer wrote:

>On Thu, 2003-05-29 at 09:40, Ryan Leathers wrote:
>  
>
>>Hi gang. I am writing an application in Java, part of which needs to add
>>the user name of a user logging onto a Linux host to a plain text list
>>of user names.  (don't worry - this is not required or intended to be
>>secure). The user will launch this application from their login script.
>>It occurred to me that the simplest way to do this was to use JNI to
>>drop to a bash shell and then mess with the file as needed in Java later
>>on.  I suppose I could just launch the script independently of the Java
>>app and get the same thing... but thats not really the point.
>>
>>I have rarely done shell scripting over the years and am looking for
>>some advice.  The lines below will do what I want, but how can I make
>>this more elegant?  Can I accomplish this without creating deleting and
>>renaming as seen below?   
>>
>>whoami > name
>>cat checked.txt name > checked.new
>>rm checked.txt
>>rm name
>>mv checked.new checked.txt
>>
>>    
>>
>
>You can do all of that in one command:
>	whoami >> checked.txt
>The double >> will open the file in "append" mode, which won't overwrite
>the existing file, so there's no need for the file juggling you show
>above.
>
>Note that doing something like this is not multiuser safe -- if this
>file is written to at the same time by multiple people, you might have
>unintended consequences.  But since you say it's not supposed to be
>"secure" maybe that won't be a problem.
>
>Also, it might be clearer to simply open the file in append mode
>directly from the Java application.  I'm not familiar with Java, but
>opening a file for appending is a basic operation that ought to be
>straight-forward in any language; hopefully someone else here will post
>how to do that.
>
>--Jeremy
>

How about this:


import java.io.RandomAccessFile;

public class sampleCode {

        public static void main(String[] args) {
                sampleCode inst = new sampleCode();
                inst.run();
        }

        private void run() {
                try{
                        String uid = System.getProperty("user.name");

                        RandomAccessFile raf = new 
RandomAccessFile("users.txt", "rw");
                        raf.skipBytes((int)raf.length());
                        raf.writeBytes(uid + "\n");
                        raf.close();

                }catch(Exception e){
                        e.printStackTrace();
                }

        }
}



-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: sampleCode.java
URL: <http://www.trilug.org/pipermail/trilug/attachments/20030529/9609bd70/attachment.ksh>


More information about the TriLUG mailing list