Originally posted by SteveRiley
View Post
Announcement
Collapse
No announcement yet.
What is your favourite Bash style?
Collapse
This topic is closed.
X
X
-
I discovered that probably the easiest way to split string in Ash or Dash is to use awk with cut.
Well, not that it was my discovery, it is just the way the Synology DS scripts do it.
First modify or print the line with awk, using separator of your choice. Then use newvar=$(echo $var | cut -d":" -f1) to get the first field, and so on.
It is possible to do it using "mount=${last##* }" but it requires just a lot more effort to devise it, although in the end it runs faster because it doesn't require 3 extra program calls.
And to get any field that is not in the beginning or the end, you have to first cut off the beginning or end so you can get to the middle.....
What do you guys do?
I still prefer the solution I have, why throw it away. But the cut version is much easier to read and devise, no-nonsense, just repetition and a few changed numbers.
- Top
- Bottom
Leave a comment:
-
Originally posted by Feathers McGraw View PostDude, you do love a good ramble.
It was you who brought up PowerShell, and dismissed it without any real reason:
So don't be offended please, but I am. Really, as the other person is saying here: why on earth should I justify my choices to you or anyone? You are apparently defending some notion, but that notion is not me and it is not even you. We can talk as normal adults or normal children (not that I have ever been either)but there is no need to mess with someone else's life, even if that person is bringing things up himself, is there? So I believe I am free to dismiss things when I want to. Now if anyone is interested in discussing that thing, sure I am willing to look into it as far as the discussion is concerned, but not much farther probably. Who knows I might stumble upon something that had never been relevant before, thanks to you people (or "Steve"). (Whom I very much respect at this point, trust me on that ;-))). It's just that "If scripting constitutes fun for you, then PowerShell deserves your attention if you use Windows." is a null-ism if we have to coin a word for it ;-).
That is like saying "If sports constitute fun for you, then American Football deserves your attention if you live in America." It doesn't follow even.
I will say that I have very good reasons for why PowerShell does NOT deserve my attention. It would have or come to be boiling down on:
- Microsoft
- dot Net
- I will easily discover design choices that I disagree with down to the smallest detail as well as the highest level
But if your only interest is in disagreeing with my choice (as Showhog would perhaps indicate?...) then that is not a real interest in debating the subject or the technology really. Because seriously. You are not asking for my reasons. You are questioning them. Questioning choices comes down to that remarkable English saying that may not even exist in another language.
When I was in that game called World of Warcraft some time ago, and you'd ask for a certain thing, such as "can you link blacksmithing?" someone would say "why not use xxxx?" And you'd go (stupidly) "because yyy" and they'd go "oh, really?".
And that site or network of sites called StackExchange is the worst of the worst in that regard. Everyone interferes with everyone. Thinking there is only one way to do a certain thing. Trying to be the one person that suggests the One Way to do a certain thing (and earn credit for it in their pointless credit or reputation system).....
Apologies if I am offending someone or anyone with that. But in English they say "There is more than one way to choke a cat." Your way does not have to be mine. I'd have to explain my goals that are really none of your business in that sense, and furthermore, you only get to those goals by trusting your instincts. Yadda yadda yadda. Bla bla bla. Life happens as a result of life happening. Not knowing where something is going is not an obstacle in getting there.
Since you said you use Windows as well as Linux, and that you want to be able to write useful scripts, don't you think the information Steve gave you was both relevant and helpful?
But... you know. The whole idea of writing POSIX compliant shell scripts is not very ...ehm.... just thinking of all the things you CAN'T do is not a very fun thing to me I must say. Why don't they just improve the POSIX standard for crying out loud? "Bashism" is a derogatory term for no reason really. The most simple of simple things are not even possible in Dash (as per https://wiki.ubuntu.com/DashAsBinSh) (yes I've read the entire thing almost). And I found the same when I was working with Ash.
Differences were most notably:
- no array expansion, no arrays in any case
- no <<< here string ( I did not know you could variables in a heredoc, at that point... until just now ;-)).
- read has (consequently) much fewer options
Well that is about what I discovered. Arrays are *pretty* useful. I was not using double brackets anyway [[ ]] mostly and it turns out you need a lot more awk/sed which is not all that bad but it requires investment. Well, the rest is not all that bad but it is like having to use a Henri David Thoreau Diet In The Woods instead of having something nice and nurturing to eat ;-).
It's really just arrays I think. And something like $RANDOM (which I've used before....).
Anyway.... every opinion is jaded by an experience, making any thought a response to a memory.
I am my enemy, can’t think my way out of this penitentiary.
Embrace the condition humanity’s mechanically accepted for centuries.
It’s the water, is it real?
How does it make you feel being endlessly dependent on external crutches and shields?
Perhaps BASH is an external crutch and shield? Or it is the other way around. Who knows. Kudos...Last edited by xennex81; Mar 05, 2015, 08:13 PM.
- Top
- Bottom
Leave a comment:
-
Let's simply agree to agree that we don't (necessarily) agree. xennex81's points are relevant to his current situation and don't require anyone else's acceptance or approval. His world view is his.
Thank you.
- Top
- Bottom
Leave a comment:
-
Dude, you do love a good ramble.
Originally posted by xennex81 View PostNo it doesn't. It doesn't coincides with my goals because to me Windows is a dead platform in that regard.
...
Come on. We are open source people, you and I ( okay I am not but still ). :P. But I really just have no interest in doing that stuff on Windows right now. It doesn't coincide with my goals in life and in computer world stuff in general.
Windows is a horror anyway in terms of scripting. They have this PowerShell but I haven't looked into it once, shying away from it as far as I can. The whole fun of being with linux is the fun of being able to script.
- Top
- Bottom
Leave a comment:
-
I have another goal which is... forgetting about life for the moment.
I may want to visit some other nightmare world at some point too.
Let me just have it, k.
Things have been *reaaly* *realy* bad but let me just forget about that. It is apparently the shortest path? I am reminded of Dijkstra's shortest path algorythm. Perhaps I shall study it again. There was also something about P-completeness. Or maybe it was about NP-completeness. That was far beyond me at that time. I just had a friend who did that stuff.
It is either called "Problem" completeness or "Not a Problem" completeness. And I have complete problems and ones that need a little work to become something worth.... I don't know. Getting sick about? I'm doing my best though.
Like they always say: but that is Japanese.
gambatte ne?Last edited by xennex81; Mar 05, 2015, 01:14 PM.
- Top
- Bottom
Leave a comment:
-
No it doesn't. It doesn't coincides with my goals because to me Windows is a dead platform in that regard. I want to work some time on introducing a new model based on ChromeOS/the old ideas for X11 and the isolation of process space from user (GUI) space, and develop a clear philosophical model for it. (I had been making the rounds on the Alpine mailing list at some point discussing it but I never really had time to check back on it yet.) I know about bashisms because yesterday I was writing a backup script (simple one) in Ash. ;-).
Ha, beat you to it just barely ;-).
My god. Nothing works in Ash. "Windows PowerShell also provides a hosting API with which the Windows PowerShell runtime can be embedded inside other applications." I want to do this with Python in Java.
Come on. We are open source people, you and I ( okay I am not but still ). :P. But I really just have no interest in doing that stuff on Windows right now. It doesn't coincide with my goals in life and in computer world stuff in general.
Being married to the Windows OS reduced portability even further. I had my fun in it in the period of 1992 to 2000 when I was coding in Pascal and Delphi, not going farther than Delphi 4 and abandoning it when it went to .NET. I am forever young. I still feel like that teenager
.
They are also treating me like a small kid here which makes it fun to annoy the ladies. Let's call them turds instead.
I am not some kind of corporate shill who requires working for Windows because of his clients all using whatever windows software they can be had with. And I never will be, I will define my own corporatism.
Okay I never thought I would be doing many things in life that I have now done to a certain extent. Sometimes you have to be what you are not in order to be what you are (such as being a rapist in order to protect women). Haha.
Situations may require of you different strategies than you would choose if it was left entirely up to you and your own devices.
Particularly /dev/eth0 may be troublesome. Indeed.
The goal of obtaining multiple variables from a single line of shell output is very daunting in Ash.
Let me state that Python by default also does not exist there once more.
Perl does though. Which is why I will use perl and C at some point. Just a little something to do with..... I WANT TO USE ScrambleDisk for Linux to create something nice. Oh man, I have so many goals and projects and they all fall into each other, they are all the same project.
I haven't been able to code from about September to right about this period, so I am trying to gain on it and I am like working day and night but sometimes I fall asleep and sometimes I bug the girls because they bug my daily rhythm with their endless calls for attention and worthlessness.
- Top
- Bottom
Leave a comment:
-
Originally posted by xennex81 View PostIt feels to me more like you eventually bailed and gave up on the 'horrors ' of bash ;-). Because from time to time (also, most of the time) it is a horror to discover that some thing you expected to work doesn't quite work that way and you die from exhaustion trying to find what it is and it is just NOT WORKING ;-). Just a personal thought. But those reasons are not ingenuitive.
http://mywiki.wooledge.org/Bashism
https://wiki.ubuntu.com/DashAsBinSh
The package devscripts has a number of interesting scripts you might be interested in studying, particularly checkbashisms.
Originally posted by xennex81 View PostWindows is a horror anyway in terms of scripting. They have this PowerShell but I haven't looked into it once, shying away from it as far as I can. The whole fun of being with linux is the fun of being able to script.If scripting constitutes fun for you, then PowerShell deserves your attention if you use Windows. It's been a feature of Windows since November 2006, so there hasn't been the old COMMAND.COM/cmd.exe "horror" for quite some time. PowerShell exposes the entire operating system to a script author. Learn more: http://en.wikipedia.org/wiki/Windows_PowerShell
- Top
- Bottom
Leave a comment:
-
It is really hard to get through to you, isn't it. Talking about you people.
No, sorry. It is like you are asking the NATO to solve your domestic problems. I see no reason for doing so. My knowledge of Windows essentials is so limited in any regard compared to Linux (even though I have been a Windows user for a .... longer number of hours than Linux, actually) that there is no point for me to try to do anything there. I have had no goals there. So why would I bother? Doing something that doesn't exist?
And besides, should I ever want to do that thing, it would come after a lot of other things that would cause me to learn python, I have no reason to learn python to do a thing I don't want to do so I cannot get to the things I want to do which would cause me to naturally learn it ;-).
And by that time (probably a few years away, the way things are going now??
) Windows will probably not even be the same anymore. But we shall see.
- Top
- Bottom
Leave a comment:
-
Originally posted by xennex81 View PostBut in Windows you would *also* not use python to do regular system tasks. Simply because it is too high-level for that, too alien to the core system for that.
Originally posted by xennex81 View PostWindows is a horror anyway in terms of scripting.
- Top
- Bottom
Leave a comment:
-
Originally posted by andystmartin View PostTry distributing your bash script to a Windows machine. To me, it seems much less likely that bash has been installed on Windows than Python..
In Python, there is no C-style "switch/case" statement. The silliness of this is debatable. The Python gurus argue that any small switch statement is equivalent to "if/else if/else if/else". They also argue that any long switch statement is better replaced with a dictionary of functions indexed by the case condition. That being said, lack of switch/case doesn't stop me from using Python.
Agreed, bash is highly useful for small or short-lived scripts -- if that's what you mean by "regular shell scripts". My point was that whenever I must maintain a script for more than a day or two and if it is more complex than can be done in about 10 to 20 lines, I include Python as one of the tools I might choose.
It feels to me more like you eventually bailed and gave up on the 'horrors ' of bash ;-). Because from time to time (also, most of the time) it is a horror to discover that some thing you expected to work doesn't quite work that way and you die from exhaustion trying to find what it is and it is just NOT WORKING ;-). Just a personal thought. But those reasons are not ingenuitive.
You don't write shell scripts for system configuration that you then want to port to Windows. Windows is a horror anyway in terms of scripting. They have this PowerShell but I haven't looked into it once, shying away from it as far as I can. The whole fun of being with linux is the fun of being able to script. And Python.... I will use that for other things ;-). I have to reboot though. I was trying my hand at installing a "penetration testing" ;-) distribution but I thought I would be clever enough to be capable of thinking that I would be able to manage to not install a bootloader for it and just make my way through Grub. Currently this system is being loaded by Kubuntu's initrd. It works fine after copying Kubuntu's /lib/modules to it but its initrd has these really cool text-mode tty and I want to get it loaded, but problems. ;-). Later
Last edited by xennex81; Mar 04, 2015, 12:10 PM.
- Top
- Bottom
Leave a comment:
-
Originally posted by xennex81 View Post...
But that isn't what I was asking. Perhaps my question was a little disingenuitive. I cannot really see how Python scripts are easier to modify and distribute.
But there is also silliness. I don't remember. There not being any for loop?
I guess, and that's the point of all of this, there is a tool for everything. I just think that Python is not suited for Bash scripts or the style of regular shell scripts because:
...
- Top
- Bottom
Leave a comment:
-
Long rave. ☺
Discussing style without examples is difficult. I wonder if it would be good to post an example script, for us to propose different styles? As I said earlier, a lot of bash scripts are handicapped by styles originating in shells much less capable than bash.
[edit]For example, output is piped through sed or cut. The constructs ${parameter/pattern/string} or ${parameter:offset:length} may do those jobs more cleanly and far faster.
Regards, John Little
- Top
- Bottom
Leave a comment:
-
I know what Python is. Not that I've used it extensively, but I want to. I have only written a test program to put some old DOS program of myself into GTK(2).
But that isn't what I was asking. Perhaps my question was a little disingenuitive. I cannot really see how Python scripts are easier to modify and distribute. For one, it is a more extensive language by far and for that reason the wish or desire or opportunity for learning it "by chance" or "as you go" as it were is a lot slimmer.
I'm just saying the number of people willing to learn Python to make a few scripts in the shell is a lot smaller than those willing to mess about with Bash for a while. I am saying that because "man bash" is enough to get a good bearing on what to do and you can just observe existing scripts and they don't require a python interpreter, nor do you have to deal with version issues (2 > 3). The madness surrounding the move to Python 3 is incredible. I have had to print on paper the various features that a certain migration library provided. It is not here and I am not sure exactly anymore what is was. I think it was something to enable access to 3 features to 2 programs. Because personally I intend to develop for version 2 still and not go with version 3.
Python 3, I must and may say, is one of those advances that the community or the world in general (the programmers) find a hard time accepting. And then those people pushing it, really start pushing it. "There is no reason to stick to 2." But if half the world sticks to 2, apparently there is a very good reason for it. All the same, there is also SQlite version 2 that is still very much around. For reasons probably that version 3 introduced complexity and made the (binary) format more complex, things to do with UTF8 also.
Python is ubiquitous, that's true. There are even a few dozen python packages for my Synology NAS. That "few dozen" is actually 175 packages that have "python" in the name excluding one thing that just mentioned that it was written in it.
And it may be the most elegant language I have ever seen. Not that the GTK coding proved to be that easy, but that aside. But there is also silliness. I don't remember. There not being any for loop? I guess, and that's the point of all of this, there is a tool for everything. I just think that Python is not suited for Bash scripts or the style of regular shell scripts because:
- the scope of the language is much larger; you don't necessarily use the GNU tools that are available in a unix system, as such it is less modular from that point of view, these are tools you may want to use anyhow. It is, to my light, essential that you learn how to use find, grep, and many other commands. Shell scripts can be created on the command prompt, and they are required for bash configuration files. Being dependent on another interpreter is not a good thing and may cause problems when you need to work on smaller or even embedded systems.
- the program you created in Python is like one of the base unix utilities that I just mentioned.
- writing Python puts you into the mood of writing a "real program" instead of a script. It is a bit of a longer thing and you may want to push your goals higher when doing so, thereby requiring more dedication at least from my point of view. Personally I always try to make do with least amount of effort required to have fun. Doing stuff in advance of something else is something I don't like. I just go ahead and work my way through the madness and the mazes.
- I personally want to use Python to write a (cronned) (or something) website backend, like a data mining thing or store. I also want it to interface with PHP. I also want to use it to write a Java server application and have Python as a scripting engine that gets linked directly as a form of library inclusion (so not using the command line program, but just a python lib that executes the interpreter and an API that I can use from Java).
- even though Bash is really terse (you should see the style I have developed now) with many commands on a single line, this is actually an advantage from a scripting (shell scripting) POV. Since the constructs bash uses are always the same (apart from really far-off constructs the way you can see them in "configure" scripts, those are really advanced. Unreadable. But the regular style that I am using is always the same, so it is not even that hard to read as soon as you are accustomed to it.
- the advantages you mentioned are not advantages for a shell script. Enforced indentation is something I do for myself when I have the time or desire to make it pretty. Multiple execute statements on a single line does not happen all that easily in Bash because your lines in a terminal window are just not that long. As a programmer you usually stick to lines of 80 or 100 or 120 characters anyway. It is very easy in Bash to break lines and indent. The style I have now makes for very easy branching and if you stick to a certain format you won't make all that many mistakes, although there is still in this current style of mine a risk to mis-assess what the thing is going to do on this planet of earth and beyond.
I like playing with fire now and then.
I am really doing weird stuff in Bash out of my desire not to use all that much exit statements and the like.
My apologies for not posting this message earlier. I guess I was not done. So people responded before I did. Well, whatever.Last edited by xennex81; Mar 04, 2015, 02:24 AM.
- Top
- Bottom
Leave a comment:
-
Sounds interesting, please do! Python is something I've never tried but had been bumped up my list quite a bit recently...
timestamp localtime UTCtime.
Hope this helps.
Code:#! /usr/bin/env python import time as _time from datetime import datetime import dateutil.parser from dateutil.tz import tzfile import sys class Time(object): def __init__(self): self.tz = tzfile('/etc/localtime') self.utc = tzfile('/usr/share/zoneinfo/UTC') self.dt = None def convert_to_datetime(self, timeStr): try: # If the string is an integer, it's a timestamp timestamp = int(str(timeStr), 0) except ValueError: # Try parsing with dateutil try: # self.dt = dateutil.parser.parse(timeStr) self.dt = dateutil.parser.parse(timeStr).replace(tzinfo=self.tz) except ValueError: # Unable to parse time string or convert to int raise else: self.dt = datetime.fromtimestamp(timestamp, self.tz) def format_time(self, utc=False): timeStr = '' if self.dt is not None: dt = self.dt if utc: dt = dt.replace(tzinfo=self.utc) - dt.utcoffset() timeStr = dt.strftime('%a, %b %d, %Y %H:%M:%S (%Z)') return timeStr def get_timestamp(self): t = 0 if self.dt is not None: t = int(_time.mktime(self.dt.timetuple())) return t def main(): now = int(_time.time()) t_manip = Time() ts = sys.argv[1:] if len(ts) == 0: # With no arguments, print current time. ts.append(now) for s in ts: try: t_manip.convert_to_datetime(s) except ValueError as e: print "* Exception (%s): '%s'" % (str(e), s) print ' must be integer or yyyy-mm-ddThh:mm:ss string' continue print '%10d ' % t_manip.get_timestamp(), print t_manip.format_time(), print t_manip.format_time(utc=True) if __name__ == '__main__': main()
- Top
- Bottom
Leave a comment:
Leave a comment: