Re: Bash Scripting Question
Jonathan Dowland j...@debian.org wrote: On Sun, Nov 03, 2013 at 09:58:58PM +0100, Erwan David wrote: Maybe you'll need something like expect to handle this. I'd second expect, it's probably the best tool for the job in all non-trivial cases. The empty-expect package, perhaps? Chris -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/e2vskaxd2t@news.roaima.co.uk
Re: Bash Scripting Question
On 11/4/13, Thomas H. George li...@tomgeorge.info wrote: The script I am trying to write executes a program that requires a keyboard response. I have experimented with redirecting STDIN but haven't found the correct way to make the response. To read a value (perhaps half your problem): apt-cache show ... zenity # gnome kdialog # kde xdialog # x generic expect # Tk (not sure I understand expect) dialog or whiptail #curses (text) http://code.google.com/p/yad/ # xenity fork with many improvements Good luck, Zenaan -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/caosgnsqrh+2g7issiazssiwhztskydovx459ubygf4frsru...@mail.gmail.com
Re: Bash Scripting Question
The tool 'yes' can be used to write an infinite stream of strings (the default being 'y') to standard output, so if your program needed only a sequence of a fixed string such as 'y', you could do yes | your-program or yes some-other-string | your-program But if your program is not reading strictly from standard input (there are other ways to get keyboard/interactive input), then… On Sun, Nov 03, 2013 at 09:58:58PM +0100, Erwan David wrote: Maybe you'll need something like expect to handle this. I'd second expect, it's probably the best tool for the job in all non-trivial cases. -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20131104100536.ga2...@bryant.redmars.org
Re: Bash Scripting Question
Hi On Sun, Nov 03, 2013 at 02:35:30PM -0500, Thomas H. George wrote: The script I am trying to write executes a program that requires a keyboard response. I have experimented with redirecting STDIN but haven't found the correct way to make the response. I found one example that scanned the response from apt-get install for the letter y and fed this back to install . In my case I must respond with a word in answer to the programs question. Well - if you're trying to script a command, have a closer look at the man-page for the command in question: There may be ways of making the command non-interactive: Then you don't have to give it any input at all! If you are trying to script the apt-get install command, check out the --yes option and it's relatives. Note that apt WILL ask if you're trying to do crazy stuff, e.g. like removing essential packages. Even the simpler questions are there to give you a chance not to shoot yourself in the foot: If you script the answers to them, your (metaphorical) foot is in danger... I'm sure this must be elementary but I have read large sections of BASH GUIDE FOR BEGINNERS and AVANCED BASH-SCRIPTING GUIDE without finding a solution. I would appreciate a little help or advice. :-) Good - that's definitely worth reading. -- Karl E. Jorgensen -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20131104121304.GA10450@hawking
Bash Scripting Question
The script I am trying to write executes a program that requires a keyboard response. I have experimented with redirecting STDIN but haven't found the correct way to make the response. I found one example that scanned the response from apt-get install for the letter y and fed this back to install . In my case I must respond with a word in answer to the programs question. I'm sure this must be elementary but I have read large sections of BASH GUIDE FOR BEGINNERS and AVANCED BASH-SCRIPTING GUIDE without finding a solution. I would appreciate a little help or advice. Tom -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20131103193530.ga22...@tomgeorge.info
Re: Bash Scripting Question
The script I am trying to write executes a program that requires a keyboard response. A varaible can be set to a keyboard response using a read prompt read -e -p What do you need ? xVariable echo $xVariable -- Stanley C. Kitching Human Being Phoenix, Arizona -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/l56bqj$62c$1...@dont-email.me
Re: Bash Scripting Question
Le 03/11/2013 20:35, Thomas H. George a écrit : The script I am trying to write executes a program that requires a keyboard response. I have experimented with redirecting STDIN but haven't found the correct way to make the response. I found one example that scanned the response from apt-get install for the letter y and fed this back to install . In my case I must respond with a word in answer to the programs question. I'm sure this must be elementary but I have read large sections of BASH GUIDE FOR BEGINNERS and AVANCED BASH-SCRIPTING GUIDE without finding a solution. I would appreciate a little help or advice. Tom Maybe you'll need something like expect to handle this. -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/5276b912.1080...@rail.eu.org
variables en bash-scripting
IP1=1 2 3 4 IPA=a b c n=1 ip=IP$n for x in ***ip***; do bla; bla done En lugar de ***ip*** yo ponia ${!ip} y funcionaba (al menos en el bash del CENTOS), pero en debian7 no funciona Y no sé cómo hacer la pregunta respectiva al google, de ahí esta consulta. Una mano, por favor. Saludos. -- [o - - - -- - (\ | u d t ( \_(' c c s (__(=_) s o ? -=
Re: variables en bash-scripting
El día 21 de mayo de 2013 10:29, Mariano Cediel mariano.ced...@gmail.com escribió: IP1=1 2 3 4 IPA=a b c n=1 ip=IP$n for x in ***ip***; do bla; bla done En lugar de ***ip*** yo ponia ${!ip} y funcionaba (al menos en el bash del CENTOS), pero en debian7 no funciona Y no sé cómo hacer la pregunta respectiva al google, de ahí esta consulta. Una mano, por favor. Saludos. Pues funciona. Seguro que usas bash? $ P1=1 2 3 4 $ ip=IP1 $ for x in ${!ip}; do echo $x; done 1 2 3 4 S2 -- To UNSUBSCRIBE, email to debian-user-spanish-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/CAGw=rHi264Yûzngzzmhzbeabytwdy5q9po3svc5jm2zkj...@mail.gmail.com
Re: variables en bash-scripting
El Tue, 21 May 2013 10:29:13 +0200, Mariano Cediel escribió: IP1=1 2 3 4 IPA=a b c n=1 ip=IP$n for x in ***ip***; do bla; bla done En lugar de ***ip*** yo ponia ${!ip} y funcionaba (al menos en el bash del CENTOS), Pues en lenny lo ejecuta. pero en debian7 no funciona ¿Qué error te saca? Y no sé cómo hacer la pregunta respectiva al google, de ahí esta consulta. Supongo que buscaras por esto: http://www.enricozini.org/2008/tips/bash-indirection/ Saludos, -- Camaleón -- To UNSUBSCRIBE, email to debian-user-spanish-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/kng1gh$1n2$8...@ger.gmane.org
Re: variables en bash-scripting [SOLUCIONADO]
El 21 de mayo de 2013 16:48, Camaleón noela...@gmail.com escribió: El Tue, 21 May 2013 10:29:13 +0200, Mariano Cediel escribió: IP1=1 2 3 4 IPA=a b c n=1 ip=IP$n for x in ***ip***; do bla; bla done En lugar de ***ip*** yo ponia ${!ip} y funcionaba (al menos en el bash del CENTOS), Pues en lenny lo ejecuta. pero en debian7 no funciona ¿Qué error te saca? Y no sé cómo hacer la pregunta respectiva al google, de ahí esta consulta. Supongo que buscaras por esto: http://www.enricozini.org/2008/tips/bash-indirection/ Saludos, -- Camaleón -- To UNSUBSCRIBE, email to debian-user-spanish-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/kng1gh$1n2$8...@ger.gmane.org Error MIO estaba debugando con sh -x script.sh y además en la cabecera estaba poniendo #!/bin/sh en lugar de #!/bin/bash Saludos y gracias. -- [o - - - -- - (\ | u d t ( \_(' c c s (__(=_) s o ? -= -- To UNSUBSCRIBE, email to debian-user-spanish-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/cab-01r6ftuhhn9mfalkfxxrfa5sohsp_baqwuy0ndpghrx5...@mail.gmail.com
Re: OT: A question about bash scripting
Ralf Mardorf ralf.mard...@alice-dsl.net wrote: month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) You've got a horrible race condition in there just waiting to bite you. Try this instead: done=$(date +%s) month=$(date --date @$done +%B) mon=$(date --date @$done +%b) d_y_t=$(date --date @$done +'/%d/%Y %T') Chris -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/7ud4m9xtms@news.roaima.co.uk
Re: OT: A question about bash scripting
On Tue, 30 Oct 2012 08:58:31 +0100, Chris Davies chris-use...@roaima.co.uk wrote: done=$(date +%s) month=$(date --date @$done +%B) mon=$(date --date @$done +%b) d_y_t=$(date --date @$done +'/%d/%Y %T') I agree, good idea. -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/op.wmzth9s8qhadp0@suse11-2
Re: OT: A question about bash scripting
On Mon, 2012-10-29 at 15:00 -0400, Wolf Halton wrote: On Mon, Oct 29, 2012 at 6:57 AM, Ralf Mardorf ralf.mard...@alice-dsl.net wrote: Hi :) how can I get rid of the variable seconds? ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} ^^^ the math should replace the variable. ### Killall and Restore session started=$(date +%s) bash $song_path/session/start-session-$startversion ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo TIA, Ralf Ralf, I don't understand. What are you wanting to do with the script? If you don't like the name of the variable, make up another one. Wolf This part of a larger script is a stopwatch and I want the math ((done-started)-(((done-started)/60)*60)+100)) inside the formatted string ${seconds: -2} , instead of a variable. Something similar to ${((done-started)-(((done-started)/60)*60)+100)): -2} Similar, because I'm missing something. Regards, Ralf PS: In German: Das ${seconds: -2} formatiert den String und statt seconds soll dort ((done-started)-(((done-started)/60)*60)+100)) eingefügt werden. Doch wie? -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/1351538780.1119.14.camel@localhost.localdomain
Re: OT: A question about bash scripting
On Monday, October 29, 2012 03:26:20 PM Ralf Mardorf wrote: On Mon, 2012-10-29 at 15:00 -0400, Wolf Halton wrote: On Mon, Oct 29, 2012 at 6:57 AM, Ralf Mardorf ralf.mard...@alice-dsl.net wrote: Hi :) how can I get rid of the variable seconds? ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} ^^^ the math should replace the variable. ### Killall and Restore session started=$(date +%s) bash $song_path/session/start-session-$startversion ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo TIA, Ralf Ralf, I don't understand. What are you wanting to do with the script? If you don't like the name of the variable, make up another one. Wolf This part of a larger script is a stopwatch and I want the math ((done-started)-(((done-started)/60)*60)+100)) inside the formatted string ${seconds: -2} , instead of a variable. Something similar to ${((done-started)-(((done-started)/60)*60)+100)): -2} Similar, because I'm missing something. You missed the $((...)) syntax as exemplified by the '(done-started)/60' just before it: min_sec=$(((done-started)/60)): min_sec=${min_sec}$(((done-started)-(((done-started)/60)*60)+100))
Re: OT: A question about bash scripting
On Mon, 2012-10-29 at 15:59 -0400, Neal Murphy wrote: On Monday, October 29, 2012 03:26:20 PM Ralf Mardorf wrote: On Mon, 2012-10-29 at 15:00 -0400, Wolf Halton wrote: On Mon, Oct 29, 2012 at 6:57 AM, Ralf Mardorf ralf.mard...@alice-dsl.net wrote: Hi :) how can I get rid of the variable seconds? ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} ^^^ the math should replace the variable. ### Killall and Restore session started=$(date +%s) bash $song_path/session/start-session-$startversion ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} echo echo Attended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo TIA, Ralf Ralf, I don't understand. What are you wanting to do with the script? If you don't like the name of the variable, make up another one. Wolf This part of a larger script is a stopwatch and I want the math ((done-started)-(((done-started)/60)*60)+100)) inside the formatted string ${seconds: -2} , instead of a variable. Something similar to ${((done-started)-(((done-started)/60)*60)+100)): -2} Similar, because I'm missing something. You missed the $((...)) syntax as exemplified by the '(done-started)/60' just before it: min_sec=$(((done-started)/60)): min_sec=${min_sec}$(((done-started)-(((done-started)/60)*60)+100)) I want ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} in one line, instead of two lines. I don't understand your reply. Even if I would add ${min_sec: 2} to each echo command (there will be a second output to a log file, it wouldn't be formatted as needed. FOR YOUR EXAMPLE, IIUC IT SHOULD BE? ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) #((seconds=(done-started)-(((done-started)/60)*60)+100)) #min_sec=$(((done-started)/60)):${seconds: -2} min_sec=$(((done-started)/60)):$(((done-started)-(((done-started)/60)*60)+100)) echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... RESULT ... Attended time to restore session: 0:102 Session restored at October/29/2012 21:11:43 ... RESP. ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) #((seconds=(done-started)-(((done-started)/60)*60)+100)) #min_sec=$(((done-started)/60)):${seconds: -2} min_sec=$(((done-started)/60)):$(((done-started)-(((done-started)/60)*60)+100)) min_sec=${min_sec: 2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... RESULT ... Attended time to restore session: 102 Session restored at October/29/2012 21:17:26 BUT I NEED ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... THIS RESULT ... Attended time to restore session: 0:02 Session restored at October/29/2012 21:21:32 ... WHILE I WONT THIS 2 lines, AS ONE LINE, INCLUDING THE FORMATTING: ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} Regards, Ralf -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/1351542663.1119.40.camel@localhost.localdomain
Re: OT: A question about bash scripting
... WHILE I WONT THIS 2 lines, AS ONE LINE, INCLUDING THE FORMATTING: Oops, an evil typo ;), it should be ... while I want. The capital letters aren't for shouting, just to distinguish the mail's text from the script. -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/1351543007.1119.44.camel@localhost.localdomain
Re: OT: A question about bash scripting
On 29/10/12 20:31, Ralf Mardorf wrote: (trimmed) I want ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} in one line, instead of two lines. I don't understand your reply. Even if I would add ${min_sec: 2} to each echo command (there will be a second output to a log file, it wouldn't be formatted as needed. FOR YOUR EXAMPLE, IIUC IT SHOULD BE? ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) #((seconds=(done-started)-(((done-started)/60)*60)+100)) #min_sec=$(((done-started)/60)):${seconds: -2} min_sec=$(((done-started)/60)):$(((done-started)-(((done-started)/60)*60)+100)) echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... RESULT ... Attended time to restore session: 0:102 Session restored at October/29/2012 21:11:43 ... RESP. ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) #((seconds=(done-started)-(((done-started)/60)*60)+100)) #min_sec=$(((done-started)/60)):${seconds: -2} min_sec=$(((done-started)/60)):$(((done-started)-(((done-started)/60)*60)+100)) min_sec=${min_sec: 2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... RESULT ... Attended time to restore session: 102 Session restored at October/29/2012 21:17:26 BUT I NEED ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... THIS RESULT ... Attended time to restore session: 0:02 Session restored at October/29/2012 21:21:32 ... WHILE I WONT THIS 2 lines, AS ONE LINE, INCLUDING THE FORMATTING: ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} Would this do what you are after? ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) echo printf Attended time to restore session: %4d:%02d\n $(((done-started)/60)) $(((done-started)%60)) printf Session restored at %9.9s%s\n $month $d_y_t echo (The first printf is a long line that will probably get spilt by email. It should all be on one line). Also the SECONDS shell counter variable is useful for this sort of thing. For example: ### Killall and Restore session SECONDS=0 ... done=$SECONDS -- Dom -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/508ef5cd.8070...@rpdom.net
Re: OT: A question about bash scripting
On Monday, October 29, 2012 04:31:03 PM Ralf Mardorf wrote: FOR YOUR EXAMPLE, IIUC IT SHOULD BE? ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) #((seconds=(done-started)-(((done-started)/60)*60)+100)) #min_sec=$(((done-started)/60)):${seconds: -2} min_sec=$(((done-started)/60)):$(((done-started)-(((done-started)/60)*60 )+100)) echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... RESULT ... Attended time to restore session: 0:102 Session restored at October/29/2012 21:11:43 ... RESP. ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) #((seconds=(done-started)-(((done-started)/60)*60)+100)) #min_sec=$(((done-started)/60)):${seconds: -2} min_sec=$(((done-started)/60)):$(((done-started)-(((done-started)/60)*60 )+100)) min_sec=${min_sec: 2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... RESULT ... Attended time to restore session: 102 Session restored at October/29/2012 21:17:26 BUT I NEED ... ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ... THIS RESULT ... Attended time to restore session: 0:02 Session restored at October/29/2012 21:21:32 ... WHILE I WONT THIS 2 lines, AS ONE LINE, INCLUDING THE FORMATTING: ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} Regards, Ralf What's the '+100' supposed to do? Add 100 to the remaining seconds? Or subtract 100 from it? (That is, increase or decrease the number of seconds?) The way it is now, the number of seconds will never be less than 100 and your ': -2' tweak will never trigger anyway. What you are asking cannot be done. You cannot nest substitutions in the manner you wish, and getting the leading zero on the seconds is problematic using only bash. I don't think you can put that many conditionals on a single line and have it remain comprehendable. However, you might be able to do it using awk: ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) min_sec=$(((done-started)/60)):$(echo $done $started | awk '{s=($1-$2)%60; if (s==0) {s=2;} printf (%2.2d, s);}') echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo But regardless, the line is going to be rather long. Unless you use a shell function: getSeconds () { echo $done $started | \ awk '{ s=($1-$2)%60; if (s==0) {s=2;} printf (%2.2d, s); }' Then use: min_sec=$(((done-started)/60)):$(getSeconds) But I still don't see what the '+100 is supposed to do.
Re: OT: A question about bash scripting
On Mon, 2012-10-29 at 21:31 +, Dom wrote: Would this do what you are after? ### Killall and Restore session started=$(date +%s) sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) echo printf Attended time to restore session: %4d:%02d\n $(((done-started)/60)) $(((done-started)%60)) printf Session restored at %9.9s%s\n $month $d_y_t echo (The first printf is a long line that will probably get spilt by email. It should all be on one line). Also the SECONDS shell counter variable is useful for this sort of thing. For example: ### Killall and Restore session SECONDS=0 ... done=$SECONDS Thank you :) that's it. started=$(date +%s) SECONDS=0 sleep 72 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) done_2=$SECONDS ((seconds=(done-started)-(((done-started)/60)*60)+100)) min_sec=$(((done-started)/60)):${seconds: -2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ((min=(done_2/60))) ; ((sec=(done_2%60))) echo printf Attended time to restore session: %9d:%02d\n $min $sec printf Session restored at %9.9s%s\n $month $d_y_t echo ### Log file grep Write to log file enabled. $log_file /dev/null if [ $? -eq 0 ] ; then echoRestore: $min_sec $mon$d_y_t $log_file printfRestore: %s:%02d %s%s\n $min $sec $mon $d_y_t $log_file fi Regards, Ralf -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/1351552967.1119.52.camel@localhost.localdomain
[sloved] OT: A question about bash scripting
On Mon, 2012-10-29 at 18:52 -0400, Neal Murphy wrote: What's the '+100' supposed to do? ### Killall and Restore session started=$(date +%s) SECONDS=0 sleep 2 ### Time month=$(date +%B) mon=$(date +%b) d_y_t=$(date '+/%d/%Y %T') done=$(date +%s) done_2=$SECONDS ((seconds=(done-started)-(((done-started)/60)*60))) seconds=0$seconds ### THIS EXPLAINS AND REPLACES THE +100 min_sec=$(((done-started)/60)):${seconds: -2} echo echoAttended time to restore session: $min_sec echo -n Session restored at ; printf %9.9s $month ; echo $d_y_t echo ### THIS IS WHAT I LIKE THE BEST ((min=(done_2/60))) ; ((sec=(done_2%60))) echo printf Attended time to restore session: %9d:%02d\n $min $sec printf Session restored at %9.9s%s\n $month $d_y_t echo http://lists.debian.org/debian-user/2012/10/msg01286.html Regards, Ralf -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/1351554170.1119.59.camel@localhost.localdomain
una de bash scripting..
Estic segur de que es tracta de una tonteria, però no aconsegueixo resoldre-ho! tinc un script que te una durada determinada (uns 4 minuts) i m'agradaria fer algun tipus de control sobre l'execució per tal que si passessin 6 minuts s'acabés la execució. Que hauria de fer? se m'ha acudit crear un procés fill que executi un sleep 260 i després un kill, però ni se si en bash es poden fer processos fill ni m'acaba de agradar la idea... Oi que hi ha algun mètode mes simple? Gracies
Re: una de bash scripting..
El Mon, May 03, 2010 at 08:28:00PM +0200 anso - ha dit: Estic segur de que es tracta de una tonteria, pero no aconsegueixo resoldre-ho! tinc un script que te una durada determinada (uns 4 minuts) i m'agradaria fer algun tipus de control sobre l'execucio per tal que si passessin 6 minuts s'acabes la execucio. Que hauria de fer? se m'ha acudit crear un proces fill que executi un sleep 260 i despres un kill, pero ni se si en bash es poden fer processos fill ni m'acaba de agradar la idea... Oi que hi ha algun metode mes simple? aptitude install timeout :) -- Matthias Kaehlcke Embedded Linux Developer Barcelona You can chain me, you can torture me, you can even destroy this body, but you will never imprison my mind (Mahatma Gandhi) .''`. using free software / Debian GNU/Linux | http://debian.org : :' : `. `'` gpg --keyserver pgp.mit.edu --recv-keys 47D8E5D4 `- -- To UNSUBSCRIBE, email to debian-user-catalan-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20100503182926.gq3...@darwin
Re: una de bash scripting..
podries mirar de comparar l'hora d'inici del procés amb l'hora actual. L'hora d'inici del procés la pots saber amb la comanda ps aux, que té una columna anomenada START que és l'hora d'inici. Si el procés que dura 4 minuts és un bucle o és iteratiu pots executar la comparació en una subshell. De totes maneres ha d'haver una forma més bona de controlar-ho, potser per l'estat del procés, però ara mateix no se m'acudeix res. Sort! 2010/5/3 anso - ansobeg...@gmail.com Estic segur de que es tracta de una tonteria, però no aconsegueixo resoldre-ho! tinc un script que te una durada determinada (uns 4 minuts) i m'agradaria fer algun tipus de control sobre l'execució per tal que si passessin 6 minuts s'acabés la execució. Que hauria de fer? se m'ha acudit crear un procés fill que executi un sleep 260 i després un kill, però ni se si en bash es poden fer processos fill ni m'acaba de agradar la idea... Oi que hi ha algun mètode mes simple? Gracies
Re: una de bash scripting..
Perfecte! gracies a tots! Timeout no el puc instalar a la maquina on el puc executar, simplement no ho tinc permès... el primer manual era una mica avançat per a mi, però finalment amb l'exemple del marc he trobat la sol·lució! gracies a tots! P.D. No coneixia el us de $$, suposo que significa el proces pare, no? El 3 de maig de 2010 20:57, marc.ol...@grupblau.com ha escrit: Bones, Si que es poden fer threads, n'hi ha prou en posar un despres de la comanda o funció, o embolcallar les instruccions amb (). Si t'agrada o no, ja és cosa teva ;-) Aquest script funciona: - talla - #!/bin/sh ( #Això és el threat sleep 5 kill -15 $$ ) for i in 1 2 3 4 5 6 7 8 9 do echo $i sleep 1 done exit - Salut! On Mon, 3 May 2010 20:28:00 +0200, anso - ansobeg...@gmail.com wrote: Estic segur de que es tracta de una tonteria, però no aconsegueixo resoldre-ho! tinc un script que te una durada determinada (uns 4 minuts) i m'agradaria fer algun tipus de control sobre l'execució per tal que si passessin 6 minuts s'acabés la execució. Que hauria de fer? se m'ha acudit crear un procés fill que executi un sleep 260 i després un kill, però ni se si en bash es poden fer processos fill ni m'acaba de agradar la idea... Oi que hi ha algun mètode mes simple? Gracies -- Marc Olivé Grup Blau
Re: una de bash scripting..
Bones, Si que es poden fer threads, n'hi ha prou en posar un despres de la comanda o funció, o embolcallar les instruccions amb (). Si t'agrada o no, ja és cosa teva ;-) Aquest script funciona: - talla - #!/bin/sh ( #Això és el threat sleep 5 kill -15 $$ ) for i in 1 2 3 4 5 6 7 8 9 do echo $i sleep 1 done exit - Salut! On Mon, 3 May 2010 20:28:00 +0200, anso - ansobeg...@gmail.com wrote: Estic segur de que es tracta de una tonteria, però no aconsegueixo resoldre-ho! tinc un script que te una durada determinada (uns 4 minuts) i m'agradaria fer algun tipus de control sobre l'execució per tal que si passessin 6 minuts s'acabés la execució. Que hauria de fer? se m'ha acudit crear un procés fill que executi un sleep 260 i després un kill, però ni se si en bash es poden fer processos fill ni m'acaba de agradar la idea... Oi que hi ha algun mètode mes simple? Gracies -- Marc Olivé Grup Blau -- To UNSUBSCRIBE, email to debian-user-catalan-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/963a29493f113bc853a28f41b42d2...@blauconsultors.com
Re: una de bash scripting..
$$ és el PID (identificador del procés) de l'script, si. Crec que també es pot usar $BASHPID, però sempre he usat $$, és més curt i criptic i el jefe veu que soc cool, jejeje, a mes, /bin/sh que especifica l'script no te pq ser bash, així que no em fio de $BASHPID. De res! On Mon, 3 May 2010 21:04:14 +0200, anso - ansobeg...@gmail.com wrote: Perfecte! gracies a tots! Timeout no el puc instalar a la maquina on el puc executar, simplement no ho tinc permès... el primer manual era una mica avançat per a mi, però finalment amb l'exemple del marc he trobat la sol·lució! gracies a tots! P.D. No coneixia el us de $$, suposo que significa el proces pare, no? El 3 de maig de 2010 20:57, marc.ol...@grupblau.com ha escrit: Bones, Si que es poden fer threads, n'hi ha prou en posar un despres de la comanda o funció, o embolcallar les instruccions amb (). Si t'agrada o no, ja és cosa teva ;-) Aquest script funciona: - talla - #!/bin/sh ( #Això és el threat sleep 5 kill -15 $$ ) for i in 1 2 3 4 5 6 7 8 9 do echo $i sleep 1 done exit - Salut! On Mon, 3 May 2010 20:28:00 +0200, anso - ansobeg...@gmail.com wrote: Estic segur de que es tracta de una tonteria, però no aconsegueixo resoldre-ho! tinc un script que te una durada determinada (uns 4 minuts) i m'agradaria fer algun tipus de control sobre l'execució per tal que si passessin 6 minuts s'acabés la execució. Que hauria de fer? se m'ha acudit crear un procés fill que executi un sleep 260 i després un kill, però ni se si en bash es poden fer processos fill ni m'acaba de agradar la idea... Oi que hi ha algun mètode mes simple? Gracies -- Marc Olivé Grup Blau -- To UNSUBSCRIBE, email to debian-user-catalan-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/4db3707337206ce34522e4f5e27d9...@blauconsultors.com
Re: bash scripting question
Hello. I found these somewhere time ago. check if is what You need: function timer() { if [[ $# -eq 0 ]]; then echo $(date '+%s') else local stime=$1 etime=$(date '+%s') if [[ -z $stime ]]; then stime=$etime; fi dt=$((etime - stime)) ds=$((dt % 60)) dm=$(((dt / 60) % 60)) dh=$((dt / 3600)) printf '%d:%02d:%02d' $dh $dm $ds fi } This is before the command t=$(timer) and this is after the command printf 'Elapsed time: %s\n' $(timer $t) example t=$(timer) copy /dev/null /dev/zero printf 'Elapsed time: %s\n' $(timer $t) Greetings Josep El vie, 19-03-2010 a las 10:19 -0700, Mike McClain escribió: I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. now='09:07:16'; startHr=${now%%:*}; startHR=${startHr#*0}; echo $startHr; 09 str=09; str=${str#*0}; echo $str; 9 Thanks, Mike -- Satisfied user of Linux since 1997. O ascii ribbon campaign - stop html mail - www.asciiribbon.org -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/1269865700.29265.2.ca...@mail.navegants.net
Re: bash scripting question
Hi Josep, On Mon, Mar 29, 2010 at 02:28:20PM +0200, Josep M. wrote: I found these somewhere time ago. check if is what You need: snip Thanks a lot. Though my error was pointed out as a typo and corrected a while back your solution using date '+%s' is much more elegant than what I had done. Mike PS: Since I posted to and read the list you needn't email me direct. MM -- Satisfied user of Linux since 1997. O ascii ribbon campaign - stop html mail - www.asciiribbon.org -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20100329213536.gb29...@playground.mcclains.net
Re: bash scripting question
On 2010-03-29 16:35, Mike McClain wrote: [snip] Thanks a lot. Though my error was pointed out as a typo and corrected a while back your solution using date '+%s' is much more elegant than what I had done. If you want more (possibly too much) precision: $ date +'%s.%N' -- History does not long entrust the care of freedom to the weak or the timid. Dwight Eisenhower -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/4bb14146.1060...@cox.net
Re: bash scripting question
Here's something I modified as part of a benchmark script called fdtree. -- Karl Vogel I don't speak for the USAF or my company Dijkstra probably hates me. --Linus Torvalds, in kernel/sched.c #!/bin/bash # How to use xdate/xtime/persec: # # START=$(date +%s) # count=10 # xdate # tin=$(xtime) # # # do something time-consuming $count times... # tout=$(xtime) # set $(persec $tin $tout $count); ttot=$1; results=$2 # xdate # echo TIME IN, OUT, TOTAL = $tin, $tout, $ttot # echo -e \tWork per second = $results PATH=/usr/local/bin:/bin:/usr/bin export PATH function xdate # Display the date in this form: Thu, 10 Sep 2009 21:22:06.494 { set $(date +%a, %d %b %Y %T %N) ms=$(echo $6 | cut -c1-3) echo $1 $2 $3 $4 $5.$ms } function xtime # Display elapsed runtime to the millisecond. { set $(date +%s %N) sec=$(($1 - $START)) ms=$(echo $2 | cut -c1-3) echo $sec.$ms } function persec # args: start-second, finish-second, count-things # returns elapsed time and things that happened per second # to the millisecond. { start=$1 finish=$2 count=$3 if test $finish = $start; then echo 0 0 else echo $(echo scale=3; $finish-$start; $count/($finish-$start) | bc) fi } function dbg # debugging prints { test $DEBUG -gt 0 echo -e $@ } tmp=/tmp/t1$$ tmp2=/tmp/t2$$ xdate START=$(date +%s) tin=$(xtime) echo for k in 1 2 3 4 5 6 7 8 9 10 do # Read a short amount of random data. dd if=/dev/random of=$tmp2 bs=1k count=1 2 /dev/null # Duplicate it a bunch of times. cat $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp cat $tmp $tmp $tmp $tmp $tmp $tmp $tmp $tmp $tmp2 cat $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp cat $tmp $tmp $tmp $tmp $tmp $tmp $tmp $tmp $tmp2 cat $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp2 $tmp rm $tmp2 # Generate a hash. md5sum $tmp ls -l $tmp rm $tmp done echo count=10 tout=$(xtime) set $(persec $tin $tout $count); ttot=$1; results=$2 xdate echo TIME IN, OUT, TOTAL = $tin, $tout, $ttot echo -e \tWork per second = $results exit 0 -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20100330012125.34bebb...@bsd118.wpafb.af.mil
bash scripting question
I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. now='09:07:16'; startHr=${now%%:*}; startHR=${startHr#*0}; echo $startHr; 09 str=09; str=${str#*0}; echo $str; 9 Thanks, Mike -- Satisfied user of Linux since 1997. O ascii ribbon campaign - stop html mail - www.asciiribbon.org -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20100319171928.gb31...@playground.mcclains.net
Re: bash scripting question
On 2010-03-19 18:19 +0100, Mike McClain wrote: I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. Apparently bash is treating the number as octal because it starts with a leading 0. Sven -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/87bpekp5n8@turtle.gmx.de
Re: bash scripting question
On Fri, Mar 19, 2010 at 1:19 PM, Mike McClain mike.j...@nethere.com wrote: I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. now='09:07:16'; startHr=${now%%:*}; startHR=${startHr#*0}; echo $startHr; 09 str=09; str=${str#*0}; echo $str; 9 Thanks, Mike Did you wand to echo startHR and not startHr in the first expression? Stuart
Re: bash scripting question
Mike McClain wrote: I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. now='09:07:16'; startHr=${now%%:*}; startHR=${startHr#*0}; echo $startHr; 09 str=09; str=${str#*0}; echo $str; 9 Did you mean to echo $startHR - capital 'R' - in the first one? That is '9' as you are expecting ;) -- Chris Jackson Shadowcat Systems Ltd. -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/4ba3bb55.50...@shadowcat.co.uk
Re: bash scripting question
Mike McClain wrote: I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. now='09:07:16'; startHr=${now%%:*}; startHR=${startHr#*0}; echo $startHr; 09 str=09; str=${str#*0}; echo $str; I do it like this # Set date format ISO_8601='%Y-%m-%d %H:%M:%S%z' aptitude safe-upgrade date +System Upgrade Completed at: $ISO_8601/root/Admin/last-upgrade the result is Update started at : 2010-03-19 08:50:53-0400 Update completed at: 2010-03-19 08:52:19-0400 Upgrade Download started at : 2010-03-19 08:52:19-0400 Download Completed at : 2010-03-19 09:01:52-0400 System Upgrade Completed at: 2010-03-19 09:05:39-0400 HTH Wayne -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/4ba3bd88.4020...@gmail.com
Re: bash scripting question
On Fri, Mar 19, 2010 at 10:19:28AM -0700, Mike McClain wrote: snip typo right herevv now='09:07:16'; startHr=${now%%:*}; startHR=${startHr#*0}; echo $startHr; Apologies for troubling all. Mike (with egg on face) -- Satisfied user of Linux since 1997. O ascii ribbon campaign - stop html mail - www.asciiribbon.org -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20100319191837.ga32...@playground.mcclains.net
Re: bash scripting question
On Fri, Mar 19, 2010 at 06:45:15PM +0100, Sven Joachim wrote: On 2010-03-19 18:19 +0100, Mike McClain wrote: I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. Apparently bash is treating the number as octal because it starts with a leading 0. Sven In one case but not the other? What makes them treated differently? Mike -- Satisfied user of Linux since 1997. O ascii ribbon campaign - stop html mail - www.asciiribbon.org -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20100319190719.ga32...@playground.mcclains.net
Re: bash scripting question
On 20100319_101928, Mike McClain wrote: I've written a function to print elapsed time similar to /usr/bin/time but can be called at the beginning and end of a script from within the script. Occasionally I get an error: '8-08: value too great for base' It's caused by the difference in these 2 command strings but I can't for the life of me see what's going on. now='09:07:16'; startHr=${now%%:*}; startHR=${startHr#*0}; echo $startHr; 09 str=09; str=${str#*0}; echo $str; 9 Try: bgn=$(date +%s) sleep 7 end=$(date +%s) echo elapsed seconds = $(( end - bgn )) Play with values other than '7'. To actually use in a script, replace the sleep command by whatever you want to measure the elapsed time for. Expressing elapsed time as HH:MM:SS requires a little more work. To write that script, use / for divide operator and % for remainder operator, like in C. -- Paul E Condon pecon...@mesanetworks.net -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/20100319194539.gh7...@big.lan.gnu
Re: bash scripting question
Paul E Condon wrote: Try: bgn=$(date +%s) sleep 7 end=$(date +%s) echo elapsed seconds = $(( end - bgn )) You might also want to experiment with: ps h -o etime $$ as long as you're happy with it only running under gnu. Prints the elapsed time for the shell. -- Chris Jackson Shadowcat Systems Ltd. -- To UNSUBSCRIBE, email to debian-user-requ...@lists.debian.org with a subject of unsubscribe. Trouble? Contact listmas...@lists.debian.org Archive: http://lists.debian.org/4ba3dae2.7080...@shadowcat.co.uk
Re: bash scripting question
Tyler Smith wrote: On 2007-05-17, Bob McGowan [EMAIL PROTECTED] wrote: Some general comments, mostly aimed at making your code cleaner without changing what it does. First, both 'echo' and 'printf' put their results on standard out. Your call of 'printf' is inside command substitution, so its STDOUT becomes --snipped stuff-- Oh, great, thanks. I added the echo to stop getting the complaint about unknown command, but this is better. So, cut and pasted from a bash shell: $ lab_num=41 $ lab_let=$(printf \x$lab_num) $ echo $lab_let A $ ((lab_num++)) $ lab_let=$(printf \x$lab_num) $ echo $lab_let B Much improved! This would need two loops, the outer to increment the 'tens' digit, the inner to increment the 'ones' digit, but it would do the trick. For example: x=(0 1 2 3 4 5 6 7 8 9 A B C D E F) I knew there was an array form in bash, but I couldn't find it. I'm working from the O'Reilly book classic shell scripting, and the only reference to arrays is in relation to awk scripts. This is a big help. Thanks alot! Tyler You're welcome ;) Bob smime.p7s Description: S/MIME Cryptographic Signature
bash scripting question
Hi, I've got a question about a short bash script I wrote. I need it to loop over a number of names, and pass a command to grass that includes two variations of those names. That was easy. Harder was getting getting a letter included in each iteration, starting with A for the first one and going up by one each iteration. What I came up with, with extra bits snipped, is: #!/bin/bash lab_num=41 for map_name in aest_90 bush_90 carol_90 comp_90 \ hirs_90 roan_90 swan_90 vir_90 ; do lab_let=$(echo -n $(printf \\x$(echo $lab_num))) echo $lab_let $map_name ${map_name}.ps ; echo $((lab_num++)) /dev/null ; done The multi-line echo is passing instructions to a GRASS command, and in the full script it works fine. This example runs fine without grass as a demonstration. What I'm wondering about is the line: lab_let=$(echo -n $(printf \\x$(echo $lab_num))) This was the only way I could figure out to loop from A to H. But since it works on hex escape codes, it won't work past 9. Is there a cleaner, more general way to do this? Thanks, Tyler -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting question
On Wed, May 16, 2007 at 08:46:37PM +, Tyler Smith wrote: Hi, I've got a question about a short bash script I wrote. I need it to loop over a number of names, and pass a command to grass that includes two variations of those names. That was easy. Harder was getting getting a letter included in each iteration, starting with A for the first one and going up by one each iteration. What I came up with, with extra bits snipped, is: #!/bin/bash lab_num=41 for map_name in aest_90 bush_90 carol_90 comp_90 \ hirs_90 roan_90 swan_90 vir_90 ; do lab_let=$(echo -n $(printf \\x$(echo $lab_num))) echo $lab_let $map_name ${map_name}.ps ; echo $((lab_num++)) /dev/null ; done The multi-line echo is passing instructions to a GRASS command, and in the full script it works fine. This example runs fine without grass as a demonstration. What I'm wondering about is the line: lab_let=$(echo -n $(printf \\x$(echo $lab_num))) This was the only way I could figure out to loop from A to H. But since it works on hex escape codes, it won't work past 9. Is there a cleaner, more general way to do this? I think there is: #!/bin/bash ( cat ! A aest_90 B bush_90 C carol_90 D comp_90 E hirs_90 F roan_90 G swan_90 H vir_90 ! ) | while read letter name do printf '%s\n%s\n%s.ps\n\n' $letter $name $name done Hope this helps -- Karl E. Jorgensen [EMAIL PROTECTED] http://www.jorgensen.org.uk/ [EMAIL PROTECTED] http://karl.jorgensen.com Today's fortune: 15% gratuity added for parties over 8. signature.asc Description: Digital signature
Re: bash scripting question
On 2007-05-16, Karl E. Jorgensen [EMAIL PROTECTED] wrote: This was the only way I could figure out to loop from A to H. But since it works on hex escape codes, it won't work past 9. Is there a cleaner, more general way to do this? I think there is: #!/bin/bash ( cat ! A aest_90 B bush_90 C carol_90 D comp_90 E hirs_90 F roan_90 G swan_90 H vir_90 ! ) | while read letter name do printf '%s\n%s\n%s.ps\n\n' $letter $name $name done Hope this helps Very much! That's perfect. Cheers, Tyler -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting question
Tyler Smith wrote: Hi, I've got a question about a short bash script I wrote. I need it to --snipped-- #!/bin/bash lab_num=41 for map_name in aest_90 bush_90 carol_90 comp_90 \ hirs_90 roan_90 swan_90 vir_90 ; do lab_let=$(echo -n $(printf \\x$(echo $lab_num))) echo $lab_let $map_name ${map_name}.ps ; echo $((lab_num++)) /dev/null ; done --snipped-- Some general comments, mostly aimed at making your code cleaner without changing what it does. First, both 'echo' and 'printf' put their results on standard out. Your call of 'printf' is inside command substitution, so its STDOUT becomes the command line for 'echo' which just prints to its STDOUT. Why the double print out? Just do: lab_let=$(printf \\x$(echo $lab_num)) Next, the 'echo $lab_num' is not needed, $lab_num can stand alone: lab_let=$(printf \\x$lab_num) And, the double quotes escape things, too, so the double backslash is not needed: lab_let=$(printf \x$lab_num) Then, the line where you increment lab_num can also be simpler. In bash the $((...)) alone on a line will replace itself with the result (command substitution, again). But, leave off the leading $ sign, and it just does the increment: ((lab_num++)) So, cut and pasted from a bash shell: $ lab_num=41 $ lab_let=$(printf \x$lab_num) $ echo $lab_let A $ ((lab_num++)) $ lab_let=$(printf \x$lab_num) $ echo $lab_let B Thanks, Tyler Since you're using bash, you may also find it convenient to put your hex digits into an array, which you can then subscript into with decimal numbers, to build the hex values needed to print other characters. This would need two loops, the outer to increment the 'tens' digit, the inner to increment the 'ones' digit, but it would do the trick. For example: x=(0 1 2 3 4 5 6 7 8 9 A B C D E F) tens=0 digits=0 while [ $tens -lt 3 ] do while [ $digits -lt 16 ] do echo ${x[$tens]}${x[$digits]} ((digits++)) done digits=0 ((tens++)) done The result is: 00 01 02 . . . 2D 2E 2F Change the 'tens' and 'digits' as needed to get the right starting value. Bob smime.p7s Description: S/MIME Cryptographic Signature
Re: bash scripting question
On 2007-05-17, Bob McGowan [EMAIL PROTECTED] wrote: Some general comments, mostly aimed at making your code cleaner without changing what it does. First, both 'echo' and 'printf' put their results on standard out. Your call of 'printf' is inside command substitution, so its STDOUT becomes the command line for 'echo' which just prints to its STDOUT. Why the double print out? Just do: lab_let=$(printf \\x$(echo $lab_num)) Next, the 'echo $lab_num' is not needed, $lab_num can stand alone: lab_let=$(printf \\x$lab_num) And, the double quotes escape things, too, so the double backslash is not needed: lab_let=$(printf \x$lab_num) Thank you for this! I started out with something a little more complicated, without the variable, trying to insert the hex character directly into another command. And my testing required that I use a form that would print something to the command line. I got very worked up trying to sort out the syntax, and obviously over-did it. Then, the line where you increment lab_num can also be simpler. In bash the $((...)) alone on a line will replace itself with the result (command substitution, again). But, leave off the leading $ sign, and it just does the increment: ((lab_num++)) Oh, great, thanks. I added the echo to stop getting the complaint about unknown command, but this is better. So, cut and pasted from a bash shell: $ lab_num=41 $ lab_let=$(printf \x$lab_num) $ echo $lab_let A $ ((lab_num++)) $ lab_let=$(printf \x$lab_num) $ echo $lab_let B Much improved! This would need two loops, the outer to increment the 'tens' digit, the inner to increment the 'ones' digit, but it would do the trick. For example: x=(0 1 2 3 4 5 6 7 8 9 A B C D E F) I knew there was an array form in bash, but I couldn't find it. I'm working from the O'Reilly book classic shell scripting, and the only reference to arrays is in relation to awk scripts. This is a big help. Thanks alot! Tyler -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting question
On Thu, May 17, 2007 at 03:40:15AM +, Tyler Smith wrote: On 2007-05-17, Bob McGowan [EMAIL PROTECTED] wrote: Some general comments, mostly aimed at making your code cleaner without changing what it does. First, both 'echo' and 'printf' put their results on standard out. Your call of 'printf' is inside command substitution, so its STDOUT becomes the command line for 'echo' which just prints to its STDOUT. Why the double print out? Just do: lab_let=$(printf \\x$(echo $lab_num)) Next, the 'echo $lab_num' is not needed, $lab_num can stand alone: lab_let=$(printf \\x$lab_num) another thing to remember is you can enclose your variable names in {} so you could do something like lab_let=$(printf \\x${lab_num}Moretext) And, the double quotes escape things, too, so the double backslash is not needed: lab_let=$(printf \x$lab_num) Thank you for this! I started out with something a little more complicated, without the variable, trying to insert the hex character directly into another command. And my testing required that I use a form that would print something to the command line. I got very worked up trying to sort out the syntax, and obviously over-did it. Then, the line where you increment lab_num can also be simpler. In bash the $((...)) alone on a line will replace itself with the result (command substitution, again). But, leave off the leading $ sign, and it just does the increment: ((lab_num++)) Oh, great, thanks. I added the echo to stop getting the complaint about unknown command, but this is better. So, cut and pasted from a bash shell: $ lab_num=41 $ lab_let=$(printf \x$lab_num) $ echo $lab_let A $ ((lab_num++)) $ lab_let=$(printf \x$lab_num) $ echo $lab_let B Much improved! This would need two loops, the outer to increment the 'tens' digit, the inner to increment the 'ones' digit, but it would do the trick. For example: x=(0 1 2 3 4 5 6 7 8 9 A B C D E F) I knew there was an array form in bash, but I couldn't find it. I'm working from the O'Reilly book classic shell scripting, and the only reference to arrays is in relation to awk scripts. This is a big help. Thanks alot! Tyler -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED] signature.asc Description: Digital signature
Mostrar listado con cabeceras y bien tabulado(bash scripting)
Eup! Estoy intentando hacer un pequeño programa en bash que pasandole como argumentos una maquina remota y un directorio, compare dicho directorio en las 2 maquinas y saque una especie de informe. El programa como tal lo tengo hecho. Lo único que a la hora de mostrar los datos queda un poco feo. Me explico: El programa tiene un menu con una serie de opciones: 1.- Ficheros solo existentes en local 2.- Ficheros solo existentes en remoto 3.- Diferencias de permisos 4.- Diferencias de propietario 5.- Diferencias de tamaño Tiene más opciones pero no viene al caso. Cuando no son muchos los ficheros diferentes no hay problema, pero si son muchos no queda bien. La cuestion es que me interesaria hacer una especie de paginacion y cabeceras (imaginaos que pulso la opcion 5 y existen 100 ficheros con tamaños diferentes) : { FicheroTam. Remoto Tam. Local - tmp500 100 messages.log 16786789 debian.iso6786888567778 kk.txt 2312 Pulse una tecla para continuar } Al pulsar la tecla nos iria sacando las siguientes paginas hasta el final: { FicheroTam. Remoto Tam. Local - passwd 45578 Fin de informe. Pulse una tecla. } La verdad es que estoy mirando varios manuales de bash pero no veo ninguno que explique este tipo de cosas.
Re: Mostrar listado con cabeceras y bien tabulado(bash scripting)
El mié, 24-01-2007 a las 17:07 +0100, gesala gesala escribió: Eup! Estoy intentando hacer un pequeño programa en bash que pasandole como argumentos una maquina remota y un directorio, compare dicho directorio en las 2 maquinas y saque una especie de informe. El programa como tal lo tengo hecho. Lo único que a la hora de mostrar los datos queda un poco feo. Me explico: El programa tiene un menu con una serie de opciones: 1.- Ficheros solo existentes en local 2.- Ficheros solo existentes en remoto 3.- Diferencias de permisos 4.- Diferencias de propietario 5.- Diferencias de tamaño Tiene más opciones pero no viene al caso. Cuando no son muchos los ficheros diferentes no hay problema, pero si son muchos no queda bien. La cuestion es que me interesaria hacer una especie de paginacion y cabeceras (imaginaos que pulso la opcion 5 y existen 100 ficheros con tamaños diferentes) : { FicheroTam. Remoto Tam. Local - tmp500 100 messages.log 16786789 debian.iso6786888567778 kk.txt 2312 Pulse una tecla para continuar } Al pulsar la tecla nos iria sacando las siguientes paginas hasta el final: { FicheroTam. Remoto Tam. Local - passwd 45578 Fin de informe. Pulse una tecla. } La verdad es que estoy mirando varios manuales de bash pero no veo ninguno que explique este tipo de cosas. ¿Sabes programar en C? Usa printf: :~$ printf %10s %10s\n $HOME $USERNAME Resultado /home/usuario usuario Pasa como parámetro el numero de caracteres que quieres que ocupe cada cadena, por ejemplo %10s imprime un string 10 caracteres (rellena con espacios si es menos, corta si es mayor) Saludos -- http://soleup.eup.uva.es/mariodebian signature.asc Description: Esta parte del mensaje está firmada digitalmente
Re: Mostrar listado con cabeceras y bien tabulado(bash scripting)
2007/1/24, gesala gesala [EMAIL PROTECTED]: Eup! Estoy intentando hacer un pequeño programa en bash que pasandole como argumentos una maquina remota y un directorio, compare dicho directorio en las 2 maquinas y saque una especie de informe. El programa como tal lo tengo hecho. Lo único que a la hora de mostrar los datos queda un poco feo. Me explico: El programa tiene un menu con una serie de opciones: 1.- Ficheros solo existentes en local 2.- Ficheros solo existentes en remoto 3.- Diferencias de permisos 4.- Diferencias de propietario 5.- Diferencias de tamaño Tiene más opciones pero no viene al caso. Cuando no son muchos los ficheros diferentes no hay problema, pero si son muchos no queda bien. La cuestion es que me interesaria hacer una especie de paginacion y cabeceras (imaginaos que pulso la opcion 5 y existen 100 ficheros con tamaños diferentes) : { FicheroTam. Remoto Tam. Local - tmp500 100 messages.log 16786789 debian.iso6786888567778 kk.txt 2312 Pulse una tecla para continuar } Al pulsar la tecla nos iria sacando las siguientes paginas hasta el final: { FicheroTam. Remoto Tam. Local - passwd 45578 Fin de informe. Pulse una tecla. } La verdad es que estoy mirando varios manuales de bash pero no veo ninguno que explique este tipo de cosas. Creo que eso lo puedes resolver con AWK, no estoy seguro. Hay un manual en español en la red que te podría ser de ayuda, no recuerdo en este momento el nombre del autor. Buena suerte. Marcos Delgado.
Re: Mostrar listado con cabeceras y bien tabulado(bash scripting)
El mié, 24-01-2007 a las 17:07 +0100, gesala gesala escribió: Eup! Estoy intentando hacer un pequeño programa en bash que pasandole como argumentos una maquina remota y un directorio, compare dicho directorio en las 2 maquinas y saque una especie de informe. El programa como tal lo tengo hecho. Lo único que a la hora de mostrar los datos queda un poco feo. Me explico: El programa tiene un menu con una serie de opciones: 1.- Ficheros solo existentes en local 2.- Ficheros solo existentes en remoto 3.- Diferencias de permisos 4.- Diferencias de propietario 5.- Diferencias de tamaño Tiene más opciones pero no viene al caso. Cuando no son muchos los ficheros diferentes no hay problema, pero si son muchos no queda bien. La cuestion es que me interesaria hacer una especie de paginacion y cabeceras (imaginaos que pulso la opcion 5 y existen 100 ficheros con tamaños diferentes) : { FicheroTam. Remoto Tam. Local - tmp500 100 messages.log 16786789 debian.iso6786888567778 kk.txt 2312 Pulse una tecla para continuar } Al pulsar la tecla nos iria sacando las siguientes paginas hasta el final: { FicheroTam. Remoto Tam. Local - passwd 45578 Fin de informe. Pulse una tecla. } La verdad es que estoy mirando varios manuales de bash pero no veo ninguno que explique este tipo de cosas. Para ir mostrando las lineas de página en página, necesitas tener todo en un fichero y tail o head (uno de los dos, y un contador) Para el formato tabulado y con cabeceras, puedes usar una cabecera #esto lo defines donde quieras cabecera=Fichero \t\t\t Tam. Remoto \t\t\t Tam.Local \n--\ -- #esto cada vez que necesites imprimir la cabecera echo -e $cabecera Para tabular los resultados, primero habría que saber como los obtienes. Pero vamos, sea como sea, mientras exista un espacio entre los tres datos, awk. es igual que la cabecera, pero sustituyendo por $1 $2 $3 los campos. Creo que si rediriges todos los datos a un fichero temporal, lego es cuestion de parsearlos (el ancho con echo + awk y el número de lineas con tail o con head) Suerte -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: Mostrar listado con cabeceras y bien tabulado(bash scripting)
On Thu, Jan 25, 2007 at 12:44:10AM +0100, Iñigo Tejedor Arrondo wrote: El mié, 24-01-2007 a las 17:07 +0100, gesala gesala escribió: Eup! Estoy intentando hacer un pequeño programa en bash que pasandole como argumentos una maquina remota y un directorio, compare dicho directorio en las 2 maquinas y saque una especie de informe. Igual y no tienes tiempo de ponerte a aprenderlo, pero perl fué escrito *exáctamente* para hacer esta clase de cosas. Si yo fuera tú, lo intentaba. -- Rodrigo Gallardo GPG-Fingerprint: 7C81 E60C 442E 8FBC D975 2F49 0199 8318 ADC9 BC28 Zenophobia: the irrational fear of convergent sequences. signature.asc Description: Digital signature
Re: bash scripting q
Ron Johnson wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 09/27/06 18:51, Hugo Vanwoerkom wrote: Hi, On my way to elapsed time in a bash script, I created the do_chrono command. It pumps the elapsed time to stdout. So if I do: a=do_chrono and then: $a I get: 0:3:19. Problem: I can't use that $a anywhere, e.g. if I say: echo $a I would expect to see 0:3:19 again, but I don't, it says do_chrono How do I use that $a in command parameters, like logger? how about b=`$a` echo $b $a -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting q
Atle Veka wrote: In your example you are saying that $a is the function 'do_chrono', so when you run $a, it runs the function and prints out the result. As another poster indicated, you need to do it slightly differently: # execute and store result in $a a=$( do_chrono ) # print echo $a Yup, that too! Thanks! H -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting q
Kevin Mark wrote: On Wed, Sep 27, 2006 at 09:22:05PM -0500, Ron Johnson wrote: how about b=`$a` echo $b or echo $($a) Bingo!!! Thanks! Is that in the Advanced Bash-Scripting Guide? H echo `$a` -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting q
Hugo Vanwoerkom wrote: Hi, On my way to elapsed time in a bash script, I created the do_chrono command. It pumps the elapsed time to stdout. So if I do: a=do_chrono and then: $a I get: 0:3:19. Problem: I can't use that $a anywhere, e.g. if I say: echo $a I would expect to see 0:3:19 again, but I don't, it says do_chrono How do I use that $a in command parameters, like logger? So this is the way it works now: #!/bin/bash a=do_chrono # elap to stdout $($a) /dev/null # Suppress output 1st call clears the chronometer(1) sleep 1 logger -t do_hibernate_prep =before sleep 4 $($a) # elap since (1)(2) sleep 4 logger -t do_hibernate_prep =after sleep 4 $($a) # elap since (2) exit 0 Produces: Sep 29 09:21:27 debian do_hibernate_prep: =do_hibernate_prep before sleep 4 0:0:1.30 Sep 29 09:21:31 debian do_hibernate_prep: =do_hibernate_prep after sleep 4 0:0:4.30 There probably are better ways of doing it. Thanks for the answers, couldn't find that in the guide... H -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting q
On Fri, Sep 29, 2006 at 08:02:38AM -0500, Hugo Vanwoerkom wrote: Kevin Mark wrote: On Wed, Sep 27, 2006 at 09:22:05PM -0500, Ron Johnson wrote: how about b=`$a` echo $b or echo $($a) Bingo!!! Thanks! Is that in the Advanced Bash-Scripting Guide? H Hi Hugo, A is used for assignment of A $A is to show the value of A $($A) is to evaluate the command string that $A returns `$A` is the old way and I think more compatible cheers, Kev -- | .''`. == Debian GNU/Linux == | my web site: | | : :' : The Universal | debian.home.pipeline.com | | `. `' Operating System| go to counter.li.org and | | `-http://www.debian.org/ |be counted! #238656 | | my keysever: pgp.mit.edu | my NPO: cfsg.org | signature.asc Description: Digital signature
Re: bash scripting q
In your example you are saying that $a is the function 'do_chrono', so when you run $a, it runs the function and prints out the result. As another poster indicated, you need to do it slightly differently: # execute and store result in $a a=$( do_chrono ) # print echo $a Atle - Flying Crocodile Inc, Unix Systems Administrator On Wed, 27 Sep 2006, Hugo Vanwoerkom wrote: Hi, On my way to elapsed time in a bash script, I created the do_chrono command. It pumps the elapsed time to stdout. So if I do: a=do_chrono and then: $a I get: 0:3:19. Problem: I can't use that $a anywhere, e.g. if I say: echo $a I would expect to see 0:3:19 again, but I don't, it says do_chrono How do I use that $a in command parameters, like logger? Thanks! H -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting q
On Wed, Sep 27, 2006 at 09:22:05PM -0500, Ron Johnson wrote: how about b=`$a` echo $b or echo $($a) echo `$a` -- | .''`. == Debian GNU/Linux == | my web site: | | : :' : The Universal | debian.home.pipeline.com | | `. `' Operating System| go to counter.li.org and | | `-http://www.debian.org/ |be counted! #238656 | | my keysever: pgp.mit.edu | my NPO: cfsg.org | signature.asc Description: Digital signature
bash scripting q
Hi, On my way to elapsed time in a bash script, I created the do_chrono command. It pumps the elapsed time to stdout. So if I do: a=do_chrono and then: $a I get: 0:3:19. Problem: I can't use that $a anywhere, e.g. if I say: echo $a I would expect to see 0:3:19 again, but I don't, it says do_chrono How do I use that $a in command parameters, like logger? Thanks! H -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: bash scripting q
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 09/27/06 18:51, Hugo Vanwoerkom wrote: Hi, On my way to elapsed time in a bash script, I created the do_chrono command. It pumps the elapsed time to stdout. So if I do: a=do_chrono and then: $a I get: 0:3:19. Problem: I can't use that $a anywhere, e.g. if I say: echo $a I would expect to see 0:3:19 again, but I don't, it says do_chrono How do I use that $a in command parameters, like logger? how about b=`$a` echo $b - -- Ron Johnson, Jr. Jefferson LA USA Is common sense really valid? For example, it is common sense to white-power racists that whites are superior to blacks, and that those with brown skins are mud people. However, that common sense is obviously wrong. -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.5 (GNU/Linux) iD8DBQFFGzHNS9HxQb37XmcRAqCmAKCkkUWs5cpymsUNFJQD66TqPmFhcgCeNsB1 Z1HAzJJ/M9T/rXAxgl0vOYQ= =YPXa -END PGP SIGNATURE- -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Bash Scripting
Hi, weiß jemand wie ich vor dem exit 0 noch ein mysql kommando ausführen kann? z.b. INSERT INTO table2 (bla, bla) VALUES(bla, bla); #! /bin/sh #benutzer anlegen mit homedir (-m) und zwei gruppen (-g -G = zweite Gruppe) USERNAME=tes HOMEDIR=/home/$USERNAME useradd -g users -G ftpuser -d $HOMEDIR $USERNAME -s /bin/bash -p `perl -e 'print crypt(ttt,Sa)'` -m cd $HOMEDIR;mkdir server #cd /home #chown -R $USERNAME $HOMEDIR exit 0 -- Mit freundlichen Grüßen Dawid Szczepanski ASCII Ribbon Campaign against HTML email -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash Scripting
Am Sonntag, 17. September 2006 21:31 schrieb Dawid Szczepanski: Hi, weiß jemand wie ich vor dem exit 0 noch ein mysql kommando ausführen kann? z.b. INSERT INTO table2 (bla, bla) VALUES(bla, bla); #! /bin/sh #benutzer anlegen mit homedir (-m) und zwei gruppen (-g -G = zweite Gruppe) USERNAME=tes HOMEDIR=/home/$USERNAME useradd -g users -G ftpuser -d $HOMEDIR $USERNAME -s /bin/bash -p `perl -e 'print crypt(ttt,Sa)'` -m cd $HOMEDIR;mkdir server #cd /home #chown -R $USERNAME $HOMEDIR mysql -u root -pxx --database=test -e 'delete from x where nam like Dauber%' exit 0 Gruß Christian Paul -- The PROPER way to handle HTML postings is to cancel the article, then hire a hitman to kill the poster, his wife and kids, and fuck his dog and smash his computer into little bits. Anything more is just extremism. -- Paul Tomblin
Re: Bash Scripting
Hallo, Am Son, 17 Sep 2006, Dawid Szczepanski schrieb: weiß jemand wie ich vor dem exit 0 noch ein mysql kommando ausführen kann? z.b. INSERT INTO table2 (bla, bla) VALUES(bla, bla); #! /bin/sh #benutzer anlegen mit homedir (-m) und zwei gruppen (-g -G = zweite Gruppe) USERNAME=tes HOMEDIR=/home/$USERNAME useradd -g users -G ftpuser -d $HOMEDIR $USERNAME -s /bin/bash -p `perl -e 'print crypt(ttt,Sa)'` -m cd $HOMEDIR;mkdir server #cd /home #chown -R $USERNAME $HOMEDIR cat 'EOF' | mysql -u user -ppassword USE database INSERT INTO table2 (bla, bla) VALUES(bla, bla); EOF exit 0 Wobei du evtl. besser das Passwort selber eingibst, d.h. mysql nur mit '-p' ohne Angabe des Passwortes angeben. Via echo, cat o.ae. kannst du beliebigen SQL-Code reinpipen. -dnh -- Eigentlich war [Indent mit tab] auch die einzige Funktion die mich an Emacs fasziniert hat -- Johannes Schmitz Wow. Das ist, wie wenn das einzige, was einen an Godzilla fasziniert, daß er ordentlich manikürte Zehnägel hat.-- David Kastrup -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash Scripting
On 2006-09-18 00:56:59 +0200, David Haller wrote: Am Son, 17 Sep 2006, Dawid Szczepanski schrieb: weiß jemand wie ich vor dem exit 0 noch ein mysql kommando ausführen kann? z.b. INSERT INTO table2 (bla, bla) VALUES(bla, bla); cat 'EOF' | mysql -u user -ppassword USE database INSERT INTO table2 (bla, bla) VALUES(bla, bla); EOF exit 0 Wobei du evtl. besser das Passwort selber eingibst, d.h. mysql nur mit '-p' ohne Angabe des Passwortes angeben. Oder per ~/.my.cnf des ausführenden Users (oder per Option aus einer anderen Datei). So ist zumindest sichergestellt, dass das Passwort nicht in der Prozessliste auftaucht (auch wenn nur für einen kleinen Augenblick). Michael -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
BASH Scripting Question
Hi all, Can someone explain to me the following behaviour? I have this script #!/bin/sh LISTS=('debian-user' 'security-basics' 'hostap' 'pen-test' 'ntbugtraq' 'ion-general' 'vim' 'madwifi'); LIST_COUNT=${#LISTS} echo $LIST_COUNT for ((i=0;i$LIST_COUNT-1;i++)); do echo /home/bhillis/Maildir/.${LISTS[${i}]}/ done But when I run it I get... 11 /home/bhillis/Maildir/.debian-user/ /home/bhillis/Maildir/.security-basics/ /home/bhillis/Maildir/.hostap/ /home/bhillis/Maildir/.pen-test/ /home/bhillis/Maildir/.ntbugtraq/ /home/bhillis/Maildir/.ion-general/ /home/bhillis/Maildir/.vim/ /home/bhillis/Maildir/.madwifi/ /home/bhillis/Maildir/./ /home/bhillis/Maildir/./ Why does $LISTS have an extra two elements than I specified? I'm following the guide from here http://techrepublic.com.com/5100-1035_11-5820685.html?part=rsstag=feedsubj=tr Thanks in advance, Byron Hillis (Metrics) -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: BASH Scripting Question
On 11/25/05, Metrics [EMAIL PROTECTED] wrote: Hi all, Can someone explain to me the following behaviour? I have this script #!/bin/sh LISTS=('debian-user' 'security-basics' 'hostap' 'pen-test' 'ntbugtraq' 'ion-general' 'vim' 'madwifi'); LIST_COUNT=${#LISTS} echo $LIST_COUNT for ((i=0;i$LIST_COUNT-1;i++)); do echo /home/bhillis/Maildir/.${LISTS[${i}]}/ done 11 is the length of the string 'debian-user'. LIST_COUNT=$((${#LISTS[*]}+1)) will give you the right number.
¿O.T? Bash Scripting
No se si es Off topic, si es asi ignorad el mensaje y mis disculpas por adelantado. Prentedo comprimir con Gzip todos los archivos que cuelgan de un determinado direrctorio (/var/proyectos) y para ello he ido averiguando un script... === for each in $(find /var/proyectos/* | grep -v .gz); do if [ -f $each ] then echo $each gzip -9f $each fi done; === Tienen que estar los ficheros uno a uno, no puedo hacer un tar de los directorios, ni inventos. El problema viene con los ficheros con nombre largo y que tienen espacio dentro del mismo (Mi Documento.doc, por ejemplo). No se exactamente que pasa, pero lo que es obvio es que no me los comprime :-( Cualquier idea/sugerencia sera bien recibida. Ah! no, no puedo renombrar los nombres... :-)
Re: ¿O.T? Bash Scripting
El Wed, Jan 19, 2005 at 04:24:19PM +0100 Txente ha dit: No se si es Off topic, si es asi ignorad el mensaje y mis disculpas por adelantado. Prentedo comprimir con Gzip todos los archivos que cuelgan de un determinado direrctorio (/var/proyectos) y para ello he ido averiguando un script... === for each in $(find /var/proyectos/* | grep -v .gz); do if [ -f $each ] then echo $each gzip -9f $each fi done; === Tienen que estar los ficheros uno a uno, no puedo hacer un tar de los directorios, ni inventos. El problema viene con los ficheros con nombre largo y que tienen espacio dentro del mismo (Mi Documento.doc, por ejemplo). No se exactamente que pasa, pero lo que es obvio es que no me los comprime :-( Cualquier idea/sugerencia sera bien recibida. Ah! no, no puedo renombrar los nombres... :-) find -type f ! -name *.gz -print -exec gzip -9f {} \; debería hacer lo que intentas hacer con el scriptillo m. -- Insanity: doing the same thing over and over again and expecting different results (Albert Einstein) ( ( ( i ) ) ) http://indymedia.org ( ( ( i ) ) ) .''`. using free software / Debian GNU/Linux | http://debian.org : :' : `. `'` gpg --keyserver keys.indymedia.org --recv-keys B9A88F6F `- signature.asc Description: Digital signature
Re: ¿O.T? Bash Scripting
On Wed, Jan 19, 2005 at 04:30:18PM +0100, matze wrote: El Wed, Jan 19, 2005 at 04:24:19PM +0100 Txente ha dit: No se si es Off topic, si es asi ignorad el mensaje y mis disculpas por adelantado. Prentedo comprimir con Gzip todos los archivos que cuelgan de un determinado direrctorio (/var/proyectos) y para ello he ido averiguando un script... === for each in $(find /var/proyectos/* | grep -v .gz); do if [ -f $each ] then echo $each gzip -9f $each ¿Y unas comillas? Así: $each. La respuesta que te dan es mejor, más elegante y eficiente, pero podrías probar lo de las comillas para salir de la duda. fi done; === Tienen que estar los ficheros uno a uno, no puedo hacer un tar de los directorios, ni inventos. El problema viene con los ficheros con nombre largo y que tienen espacio dentro del mismo (Mi Documento.doc, por ejemplo). No se exactamente que pasa, pero lo que es obvio es que no me los comprime :-( Cualquier idea/sugerencia sera bien recibida. Ah! no, no puedo renombrar los nombres... :-) find -type f ! -name *.gz -print -exec gzip -9f {} \; debería hacer lo que intentas hacer con el scriptillo m. -- Insanity: doing the same thing over and over again and expecting different results (Albert Einstein) ( ( ( i ) ) ) http://indymedia.org ( ( ( i ) ) ) .''`. using free software / Debian GNU/Linux | http://debian.org : :' : `. `'` gpg --keyserver keys.indymedia.org --recv-keys B9A88F6F `- -- pepe AT apteta DOT net / jmchalmes AT polinux DOT upv DOT es http://www.polinux.upv.es / http://www.valux.org / http://www.hispalinux.es GnuPG key = 0x6FDE933B [D5C4 12CE D6B4 E4D6 7E8E F128 405A BFAD 6FDE 933B] signature.asc Description: Digital signature
Re: ¿O.T? Bash Scripting
Hola. A ver si esto te vale: find . -name /var/proyectos/* | grep -v .gz | while read each; do echo $each if [ -f $each ]; then gzip -9f $each fi done No lo he probado, pero seguro que tira, jejejeje. Espero que te sirva. Un saludo. On Wed, 2005-01-19 at 16:24 +0100, Txente wrote: No se si es Off topic, si es asi ignorad el mensaje y mis disculpas por adelantado. Prentedo comprimir con Gzip todos los archivos que cuelgan de un determinado direrctorio (/var/proyectos) y para ello he ido averiguando un script... === for each in $(find /var/proyectos/* | grep -v .gz); do if [ -f $each ] then echo $each gzip -9f $each fi done; === Tienen que estar los ficheros uno a uno, no puedo hacer un tar de los directorios, ni inventos. El problema viene con los ficheros con nombre largo y que tienen espacio dentro del mismo (Mi Documento.doc, por ejemplo). No se exactamente que pasa, pero lo que es obvio es que no me los comprime :-( Cualquier idea/sugerencia sera bien recibida. Ah! no, no puedo renombrar los nombres... :-) -- Guillermo Rial Pinedo. Getronics Iberia C/ Miguel Yuste, 45 28037 Madrid Spain Tel: +34 91 325 3300 Fax: +34 91 754 5077 [EMAIL PROTECTED] www.getronics.es The infromation transmitted is intended only for use by the addressee and may contain confidential and/or privileged material. Any review, re-transmission, dissemination or other use of it, or the taking of any action in reliance upon this information by persons and/or entities other than the intended recipient is prohibited. If you received this in error, please inform the sender and/or addressee immediately and delete the material. Thank you. -- Clave Pública GPG - GPG Public key: http://www.rediris.es/cert/servicios/keyserver/ signature.asc Description: This is a digitally signed message part
Re: ¿O.T? Bash Scripting
On Wed, 19 Jan 2005, Txente wrote: Pretendo comprimir con Gzip todos los archivos que cuelgan de un determinado direrctorio (/var/proyectos) y para ello he ido averiguando un script... === for each in $(find /var/proyectos/* | grep -v .gz); do if [ -f $each ] then echo $each gzip -9f $each fi done; === gzip -r9 /var/proyectos/*
Re: ¿O.T? Bash Scripting
Muuucho mas elegante, sí señor. Sólo le falta añadir la ruta entre el find y el -type, por sacarle puntilla... XD On Wed, 2005-01-19 at 16:30 +0100, matze wrote: find -type f ! -name *.gz -print -exec gzip -9f {} \; debería hacer lo que intentas hacer con el scriptillo m. -- Guillermo Rial Pinedo. Getronics Iberia C/ Miguel Yuste, 45 28037 Madrid Spain Tel: +34 91 325 3300 Fax: +34 91 754 5077 [EMAIL PROTECTED] www.getronics.es The infromation transmitted is intended only for use by the addressee and may contain confidential and/or privileged material. Any review, re-transmission, dissemination or other use of it, or the taking of any action in reliance upon this information by persons and/or entities other than the intended recipient is prohibited. If you received this in error, please inform the sender and/or addressee immediately and delete the material. Thank you. -- Clave Pública GPG - GPG Public key: http://www.rediris.es/cert/servicios/keyserver/ signature.asc Description: This is a digitally signed message part
Re: ¿O.T? Bash Scripting
El Wed, Jan 19, 2005 at 04:51:39PM +0100 Santiago Vila ha dit: On Wed, 19 Jan 2005, Txente wrote: Pretendo comprimir con Gzip todos los archivos que cuelgan de un determinado direrctorio (/var/proyectos) y para ello he ido averiguando un script... === for each in $(find /var/proyectos/* | grep -v .gz); do if [ -f $each ] then echo $each gzip -9f $each fi done; === gzip -r9 /var/proyectos/* tiene el problema que volvería a comprimir los ficheros ya comprimidos, por eso txente ha puesto grep -v .gz (que por cierto debería ser '\.gz$' para no excluir ficheros como 'foogzbar.txt') m. -- Nothing is more despicable than respect based on fear (Albert Camus) ( ( ( i ) ) ) http://indymedia.org ( ( ( i ) ) ) .''`. using free software / Debian GNU/Linux | http://debian.org : :' : `. `'` gpg --keyserver keys.indymedia.org --recv-keys B9A88F6F `- signature.asc Description: Digital signature
Re: ¿O.T? Bash Scripting
On Wed, 19 Jan 2005, matze wrote: El Wed, Jan 19, 2005 at 04:51:39PM +0100 Santiago Vila ha dit: gzip -r9 /var/proyectos/* tiene el problema que volvería a comprimir los ficheros ya comprimidos, [...] No lo tiene, gzip no comprime ficheros ya comprimidos, así que no hace falta excluirlos.
Re: ¿O.T? Bash Scripting
: : UC ::: : On Wed, Jan 19, 2005 at 04:24:19PM +0100, Txente wrote: No se si es Off topic, si es asi ignorad el mensaje y mis disculpas por adelantado. Prentedo comprimir con Gzip todos los archivos que cuelgan de un determinado direrctorio (/var/proyectos) y para ello he ido averiguando un script... === for each in $(find /var/proyectos/* | grep -v .gz); do if [ -f $each ] then echo $each gzip -9f $each fi done; === Tienen que estar los ficheros uno a uno, no puedo hacer un tar de los directorios, ni inventos. El problema viene con los ficheros con nombre largo y que tienen espacio dentro del mismo (Mi Documento.doc, por ejemplo). Tienes que ocupar expresiones regulares. Puedes escapar los carateres *raros* con \ o simplemente no interpretarlos con . -- Luis Eduardo Arevalo ReyesUser #354770 counter.li.org Fono 0-91359671 http://www.inf.utfsm.cl/~larevalo Departamento de Informatica, Universidad Tecnica Federico Santa Maria
Any comments on Advance Bash-Scripting Guide?
Hi, all What do you think about the abs-guide package in debian distro? How about a `better` book on bash scripting? Hui -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: procmail recipe/bash scripting issue
On Mon, Jan 26, 2004 at 12:33:53AM -0500, Matt Price wrote: hey everyone, trying to get procmail to pipe messages to a script I wrote that processes mail to a web page. Here's the recipe: --- much snippage Hi Matt, did you do any testing? did you create a sample output and send it to the script to see if the script would work with correct output. echo correct output | . | bash script.sh -Kev signature.asc Description: Digital signature
Re: OT: procmail recipe/bash scripting issue
On 26 Jan 2004, Matt Price [EMAIL PROTECTED] wrote: So I asusme the script is running, but it's not receiving the data it needs, or at least not understanding it. Here's the script, which as ou see is very primitive: -- cat /usr/local/scripts/moviepage #!/bin/bash TITLE=`formail -xSubject: $@` ; HEADER=h2$TITLE/h2; FROM=`formail -xFrom: $@` ; BYLINE=h3$FROM/h3; BODY=`formail -I $@`; TEXT=p$BODY/p; echo $HEADER /www/derailleur.org/movies.html; echo $BYLINE /www/derailleur.org/movies.html; echo $TEXT /www/derailleur.org/movies.html; --- s... am I using the $@ wrong somehow? should I substitute somethng else? Procmail sends the message via STDIN, so you would have to read it from there. As you have to read the message more than once for the different formail calls, it would probably be best to save the message in a temporary file and read it from there afterwards. So put a msg=`tempfile`; cat $msg on top of your script and replace all $@'s with $msg. Don't forget to delete $msg when your done. -- Philipp Weis [EMAIL PROTECTED] Freiburg, Germany http://pweis.com/ -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
OT: procmail recipe/bash scripting issue
hey everyone, trying to get procmail to pipe messages to a script I wrote that processes mail to a web page. Here's the recipe: --- :0: * ? $FORMAIL -x From: | grep -isF -f /home/movies/friends_and_family.txt | /usr/local/scripts/moviepage - If I run the script from the command line iwth a message as input file, I get this: $ moviepage movietest/cur/1075094038.31194_26.anarres\:2\,S h2 Millenium Actress/h2 h3/h3 p Brilliant piece of Japanese animation, highly recommended to all. Very interesting use of comic-book tropes to do stuff that would be very hard to do with live action. And none of the stupid bloodgore that characterizes most anime. /p however, when I use the procmail recipe, I get this (same message): h2/h2 h3/h3 p/p So I asusme the script is running, but it's not receiving the data it needs, or at least not understanding it. Here's the script, which as ou see is very primitive: -- cat /usr/local/scripts/moviepage #!/bin/bash TITLE=`formail -xSubject: $@` ; HEADER=h2$TITLE/h2; FROM=`formail -xFrom: $@` ; BYLINE=h3$FROM/h3; BODY=`formail -I $@`; TEXT=p$BODY/p; echo $HEADER /www/derailleur.org/movies.html; echo $BYLINE /www/derailleur.org/movies.html; echo $TEXT /www/derailleur.org/movies.html; --- s... am I using the $@ wrong somehow? should I substitute somethng else? Thanks for your help! matt -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: bash scripting question -- passing values to ls
Matt Price [EMAIL PROTECTED] writes: here's something that ocmes up a lot for me: I use locate to find a bunch of files: % locate charter | grep -i font /usr/share/texmf/fonts/afm/bitstrea/charter /usr/share/texmf/fonts/tfm/bitstrea/charter /usr/share/texmf/fonts/type1/bitstrea/charter /usr/share/texmf/fonts/vf/bitstrea/charter then I want to ls -l each of these files... IMHO, the simplest way to do it is locate charter | grep -i font | xargs ls -l but that will fail if the filenames have spaces or other whitespace in them. The very slow but reliable equivalent would be find / -name charter -path '*charter*' -print0 | xargs -0 ls -l or even find / -name charter -path '*charter*' -ls but that doesn't do the caching that locate does. (Other people have given good suggestions about using backticks to do this as well.) -- David Maze [EMAIL PROTECTED] http://people.debian.org/~dmaze/ Theoretical politics is interesting. Politicking should be illegal. -- Abra Mitchell -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
OT: bash scripting question -- passing values to ls
hey folks, here's something that ocmes up a lot for me: I use locate to find a bunch of files: % locate charter | grep -i font /usr/share/texmf/fonts/afm/bitstrea/charter /usr/share/texmf/fonts/tfm/bitstrea/charter /usr/share/texmf/fonts/type1/bitstrea/charter /usr/share/texmf/fonts/vf/bitstrea/charter then I want to ls -l each of these files... so I have to do it by hand at the moment. But shouldn't I be able to automate it with somthing like: ls locate charter | grep -i font ? nothing I try works -- but I can't believe it's impossible! any hints? thx, matt -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: bash scripting question -- passing values to ls
On Sun, Jan 04, 2004 at 02:27:11AM -0500, Matt Price wrote: so I have to do it by hand at the moment. But shouldn't I be able to automate it with somthing like: ls locate charter | grep -i font ? nothing I try works -- but I can't believe it's impossible! any hints? I use backticks: ls `locate charter | grep -i font` -ld Some commands don't like it if you pass zillions of arguments. You can also xargs or find, but the syntax is more cumbersome, involving braces {} and crap. Somebody will probably post that syntax. -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: bash scripting question -- passing values to ls
On Sun, Jan 04, 2004 at 02:27:11AM -0500, Matt Price wrote: hey folks, here's something that ocmes up a lot for me: I use locate to find a bunch of files: % locate charter | grep -i font /usr/share/texmf/fonts/afm/bitstrea/charter /usr/share/texmf/fonts/tfm/bitstrea/charter /usr/share/texmf/fonts/type1/bitstrea/charter /usr/share/texmf/fonts/vf/bitstrea/charter then I want to ls -l each of these files... so I have to do it by hand at the moment. But shouldn't I be able to automate it with somthing like: ls locate charter | grep -i font ? nothing I try works -- but I can't believe it's impossible! any hints? thx, matt Hi Matt, I use a little bash code over and over again. Its a while loop. locate charter| grep -i font | while read line; do ls -l $line; done It has many uses and it doesnt have a limit like xargs. I found out about xargs but started having problems that it could not solve so I came up with this! Have fun with Bash! It's Bourne-Again! -Kev signature.asc Description: Digital signature
Re: OT: bash scripting question -- passing values to ls
On Sun, Jan 04, 2004 at 03:36:36AM -0500, Kevin Mark wrote: [snip] locate charter| grep -i font | while read line; do ls -l $line; done Invoking 'ls' in a loop is semantically different from invoking it once, although you can compensate for it. I prefer backticks because you can pipe the whole thing to less (although you can pipe a for loop to less, it looks messier) and you can't use the sort options of less, for example. Tomato, tomato. For loop is nice for somethings. Also starting a process per file might be more expensive than a single process with lots of args (but not in this case). -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: bash scripting question -- passing values to ls
On Sun, Jan 04, 2004 at 01:10:51AM -0800, Nano Nano wrote: [snip] it looks messier) and you can't use the sort options of less, for i meant sort options of ls -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: bash scripting question -- passing values to ls
On Sun, Jan 04, 2004 at 03:36:36AM -0500, Kevin Mark wrote: I use a little bash code over and over again. Its a while loop. locate charter| grep -i font | while read line; do ls -l $line; done It has many uses and it doesnt have a limit like xargs. I found out about xargs but started having problems that it could not solve so I came up with this! You can do the same thing with xargs. Look at the -i option. It's also good practice to quote $line like so. Cheers, -- Colin Watson [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: bash scripting question -- passing values to ls
On Sat, 03 Jan 2004 23:34:59 -0800, Nano Nano wrote: On Sun, Jan 04, 2004 at 02:27:11AM -0500, Matt Price wrote: so I have to do it by hand at the moment. But shouldn't I be able to automate it with somthing like: ls locate charter | grep -i font ? nothing I try works -- but I can't believe it's impossible! any hints? I use backticks: ls `locate charter | grep -i font` -ld Some commands don't like it if you pass zillions of arguments. You can also xargs or find, but the syntax is more cumbersome, involving braces {} and crap. Somebody will probably post that syntax. Your solution, is, of course, the most obvious and elegant (well IMHO, anyway). There's probably no need to use xargs; I just tested a similar command which returned 1,829 files and it worked OK. One thing in passing for the casual reader: there is a newer (and IMHO generally better) syntax than backquotes for command substitution: $(). No characters between $( and ) are treated specially, and, for me, the huge advantage is that nesting is easier and more readable: none of that backslash-backquote stuff to protect the nested command - some of my scripts with command subs nested 3 deep are *much* more readable :) However, in this simple case, backquotes are quicker to type than $() which is probably why Nano used them. But just for the sake of completeness: ls -ld $(locate charter | grep -i font) or, in his specific case, this would probably work: ls -ld $(locate *font*charter) Sorry, feeling a bit talkative this morning, I'll shut up now :) -- paul Programming without a hex editor is like watchmaking without a hammer. -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: OT: bash scripting question -- passing values to ls
On Sun, Jan 04, 2004 at 02:27:11AM -0500, Matt Price wrote: [...] } ls locate charter | grep -i font } ? } nothing I try works -- but I can't believe it's impossible! any } hints? locate charter | grep -i font | tr '\012' '\000' | xargs -0 ls -ld xargs is your friend. So is tr. Learn them and know them. All the other bash tricks (piping to a loop, using backticks, etc.) can give you problems with spaces and other special characters in the filenames. } thx, } matt --Greg -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Bash-Scripting
Hallo, ich versuche gerade folgendes: eine Datei: # album.alb T1=text1 T2=text2 T3=text3 ein Script: #!/bin/bash source album_001.alb count=0 while [ $count -lt 17 ] ; do let count=count+1 SONG=T$count echo $SONG done Also die Schleife funktioniert... - Nur nicht die Zeile SONG=T$count Die BASH sagt mir jedesmal: ./script: =T1: command not found Also ich gehe mal davon aus, das $count von einem arithmetischen Wert in eine Zeichenkette umgewandelt werden muß. (richtig ?) NUR WIE ? Grüße Michelle -- Registered Linux-User #280138 with the Linux Counter, http://counter.li.org. -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash-Scripting
Hello Michelle, On Thu, 1 Jan 2004 22:11:48 +0100 Michelle Konzack [EMAIL PROTECTED] wrote: Hallo, ich versuche gerade folgendes: eine Datei: # album.alb T1=text1 T2=text2 T3=text3 T[1]=text1 T[2]=text2 T[3]=text3 ein Script: #!/bin/bash source album_001.alb count=0 while [ $count -lt 17 ] ; do let count=count+1 SONG=T$count SONG=${T[$count]} echo $SONG done NUR WIE ? man bash / array Jörg -- Jörg Schütter http://www.lug-untermain.de/ [EMAIL PROTECTED] http://www.schuetter.org/joerg/ ICQ: 298982789 http://mypenguin.bei.t-online.de/ -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash-Scripting
Am Donnerstag, 1. Januar 2004 22:11 schrieb Michelle Konzack: ich versuche gerade folgendes: eine Datei: # album.alb T1=text1 T2=text2 T3=text3 ein Script: #!/bin/bash source album_001.alb count=0 while [ $count -lt 17 ] ; do let count=count+1 SONG=T$count echo $SONG done Ich weiss zwar nicht, was Du als Ergebnis haben willst (Du verrätst es uns ja nicht ;), vermute aber mal, dass in $SONG text1, text2 usw. stehen soll. Also die Schleife funktioniert... - Nur nicht die Zeile SONG=T$count Die BASH sagt mir jedesmal: ./script: =T1: command not found Also ich gehe mal davon aus, das $count von einem arithmetischen Wert in eine Zeichenkette umgewandelt werden muß. (richtig ?) Nö. schnipp #! /bin/bash . album.alb for i in `seq 0 16`; do SONG=`eval echo '$T'$i` echo $SONG done schnapp Jan -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash-Scripting
Michelle Konzack [EMAIL PROTECTED] writes: ich versuche gerade folgendes: eine Datei: # album.alb T1=text1 T2=text2 T3=text3 ein Script: #!/bin/bash source album_001.alb count=0 while [ $count -lt 17 ] ; do let count=count+1 SONG=T$count echo $SONG done Also die Schleife funktioniert... - Nur nicht die Zeile SONG=T$count Die BASH sagt mir jedesmal: ./script: =T1: command not found Bist du sicher, dass du uns oben das richtige Skript gezeigt hast? Das wirft nämlich keinen Fehler. Jedenfalls nicht den von dir genannten. Aber die erste Zeile muss source album.alb heißen. Es wäre nicht schlecht gewesen, wenn du das Gepostete auch getestet hättest, statt uns raten zu lassen. Dein Skript gibt aus: T1 T2 [... usw., bis:] T17 Also ich gehe mal davon aus, das $count von einem arithmetischen Wert in eine Zeichenkette umgewandelt werden muß. (richtig ?) Nein. Die Shell kennt nur Strings. (Es gibt zwar ein integer-Attribut, aber das ändert daran nichts - man braucht es auch nicht unbedingt zu kennen.) Ich nehme aber an, Du wolltest text1 text2 text3 als Ergebnis. Du kannst dazu zwar Arrays nehmen wie in einem anderen Posting vorgeschlagen, ich würde aber auf kein unportables bash-Konstrukt ausweichen, solange es nicht nötig ist. Mache aus SONG=T$count ein eval SONG=\$T$count Aber - wie gesagt - geraten, was das gewünschte Ergebnis anbelangt. HTH, Heike -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash-Scripting
Am 2004-01-01 22:49:52, schrieb Jörg Schütter: Hello Michelle, On Thu, 1 Jan 2004 22:11:48 +0100 Michelle Konzack [EMAIL PROTECTED] wrote: Hallo, ich versuche gerade folgendes: eine Datei: # album.alb T1=text1 T2=text2 T3=text3 T[1]=text1 T[2]=text2 T[3]=text3 ein Script: #!/bin/bash source album_001.alb count=0 while [ $count -lt 17 ] ; do let count=count+1 SONG=T$count SONG=${T[$count]} Das fabriziert ein Command not found man bash / array Ist nicht notwendig, denn die mpeg-Titel stehen ja so in der Datei also T1=Das_ist_ein_Song.mp3 T2=Debian-Song.mp3 ... Muß ja nur noch diesen blöden Zähler zum laufen bringen. Jörg Grüße Michelle -- Registered Linux-User #280138 with the Linux Counter, http://counter.li.org. -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash-Scripting
Am 2004-01-02 01:16:39, schrieb Heike C. Zimmerer: als Ergebnis. Du kannst dazu zwar Arrays nehmen wie in einem anderen Posting vorgeschlagen, ich würde aber auf kein unportables bash-Konstrukt ausweichen, solange es nicht nötig ist. Mache aus Ist auch meine meinung... SONG=T$count ein eval SONG=\$T$count Aber - wie gesagt - geraten, was das gewünschte Ergebnis anbelangt. He cool geht... Bin berade beim Downloaden von 247 mp3's ;-) Es lebe http://www.mazika.com/ HTH, Heike Noch schöne Neujahrsgrüße Michelle -- Registered Linux-User #280138 with the Linux Counter, http://counter.li.org. -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash-Scripting
Am 2004-01-02 01:21:05, schrieb Jan Trippler: #! /bin/bash . album.alb for i in `seq 0 16`; do Ach, sowas wie ne sequenz gibt es auch ? Muß mal ausprobieren... SONG=`eval echo '$T'$i` Also eine zweite Lösung... Typisch Linux. echo $SONG done Jan Danke und Neujahrsgrüße Michelle -- Registered Linux-User #280138 with the Linux Counter, http://counter.li.org. -- Haeufig gestellte Fragen und Antworten (FAQ): http://www.de.debian.org/debian-user-german-FAQ/ Zum AUSTRAGEN schicken Sie eine Mail an [EMAIL PROTECTED] mit dem Subject unsubscribe. Probleme? Mail an [EMAIL PROTECTED] (engl)
Re: Bash scripting
On Mon, 2003-03-10 at 01:02, Jeff Elkins wrote: Jeff Elkins [EMAIL PROTECTED] writes: ARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ -e s/arm.*/arm/ -e s/sa110/arm/ I'm working on polishing my meagre shell scripting skills and would appreciate some feedback on the line above, quoted from the kernel Makefile. Thanks for the replies folks! Note that if you just want to find out if this OR that is on a line or in a stream, some examples: dmesg | egrep port|connection egrep -n port|connection /var/log/dmesg -- +---+ | Ron Johnson, Jr.mailto:[EMAIL PROTECTED] | | Jefferson, LA USA http://members.cox.net/ron.l.johnson | | | | Spit in one hand, and wish for peace in the other.| | Guess which is more effective... | +---+ -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Bash scripting
ARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ -e s/arm.*/arm/ -e s/sa110/arm/ I'm working on polishing my meagre shell scripting skills and would appreciate some feedback on the line above, quoted from the kernel Makefile. 1. How would you use this in a straight bash script so it returned a value containing the boxes architecture? 2. As far as comparisons go, if I wanted to determine if a string contained .xyz or .abc would that be a variant of the fragment above? Thanks for any feedback... Jeff Elkins http://www.elkins.org -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: Bash scripting
Jeff Elkins [EMAIL PROTECTED] writes: ARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ -e s/arm.*/arm/ -e s/sa110/arm/ I'm working on polishing my meagre shell scripting skills and would appreciate some feedback on the line above, quoted from the kernel Makefile. 1. How would you use this in a straight bash script so it returned a value containing the boxes architecture? The contents of the $(shell ...) Make fragment should be a valid shell command. 2. As far as comparisons go, if I wanted to determine if a string contained .xyz or .abc would that be a variant of the fragment above? Two somewhat common ways: uname -m | grep i.86 /dev/null echo x86 case `uname -m` in i?86) echo x86 ;; esac -- David Maze [EMAIL PROTECTED] http://people.debian.org/~dmaze/ Theoretical politics is interesting. Politicking should be illegal. -- Abra Mitchell -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Re: Bash scripting
David Z Maze wrote: Two somewhat common ways: uname -m | grep i.86 /dev/null echo x86 My I suggest using 'grep -q' to save the need to redirect? case `uname -m` in i?86) echo x86 ;; esac I prefer the case statement approach. Bob pgp0.pgp Description: PGP signature