Рет қаралды 0

Пікірлер
@hmagellanlinux307
@hmagellanlinux307 4 жыл бұрын
Boomer avoids the stress of the apocalypse by obfuscating his bash scripts
@stdcall
@stdcall 4 жыл бұрын
Are you guys ready for the boog?
@superscatboy
@superscatboy 4 жыл бұрын
I'm gonna go and strip all the newlines out of my C++ code and see if it makes me feel better about myself.
@LaughingOrange
@LaughingOrange 4 жыл бұрын
@@superscatboy It could make the file smaller.
@superscatboy
@superscatboy 4 жыл бұрын
@@LaughingOrange Lol yep I've been meaning to free up a kb or two of disk space ;)
@tomaszubiri4588
@tomaszubiri4588 4 жыл бұрын
I'm starting to suspect this is a parody channel giving bad advice. Imagine someone reading your script and not knowing what || is, how do they even google that? An if is an if, everyone understands that.
@sameer26121980
@sameer26121980 3 жыл бұрын
Be careful with exit codes. They can ditch you in some cases. Also, scripting is not just for looking elegant/beautiful, it should be functional, performance tuned, easy to read/understand, easy to maintain, new-developer friendly, easy to debug, modularized and so on. Everything should be used judiciously. You will come to know what is best if you start working in real-time.
@alexanderelgert6037
@alexanderelgert6037 Жыл бұрын
Yes, you are right, we should give Luke a few hints: $ false && echo hello && echo ok $ if false; then echo hello; fi && echo ok
@Cypekeh
@Cypekeh Жыл бұрын
@@alexanderelgert6037 What is this example supposed to show? those commands are not equivalent. The second command is logically something like: $ (if false; then echo hello; fi) && echo ok Which would be equivalent to $ (false && echo hello || : ) && echo ok *brackets are unnecessary but make it easier to understand Maybe your point was that it's easy to get confused, but it's not more complicated than understanding the order of operations in mathematics
@sadface7457
@sadface7457 4 жыл бұрын
Terry Davis always said that the CASE statement was divine
@sadface7457
@sadface7457 4 жыл бұрын
Lisperati know when not if.
@btschaegg
@btschaegg 4 жыл бұрын
On that note: I wonder if there is a way of building a Duff's Device in Bash.
@timh.6872
@timh.6872 4 жыл бұрын
Not going to say it's impossible, but maybe. It'd work if you disentangle the switch from the loop, but the entire thing is academic since shells are so slow.
@nicolareiman9687
@nicolareiman9687 4 жыл бұрын
The CIA tried so hard to convince us that if/else statement is the same as switch statement but lucky for us terry teach us this divine intellect .
@lawrencedoliveiro9104
@lawrencedoliveiro9104 4 жыл бұрын
It was invented by Tony Hoare. What was remarkable was that it could be implemented with essentially zero run-time overhead. Hoare was also one of the proponents of “structured programming”. Which I feel is underrated these days, where I see C code especially using gotos like they’re going out of fashion.
@jaimesotelo4252
@jaimesotelo4252 4 жыл бұрын
You can group expressions with curly brackets: { command1 || command2 ;} && { command3 || command4 ;} Or more complex. The brackets also make it easier to understand the code IMHO. BUT what you call elegant I call ugly and bad readability. I use this in my code but at least I don’t claim it to be beautiful or elegant. You got a negative from me today.
@bwcbiz
@bwcbiz 4 жыл бұрын
You and I have different definitions of "elegance". I can understand your preference for concise code, which is the traditional spirit of Unix/Linux. I, on the other hand, want my code to be readable by newbs in a corporate environment long after I've gone. I don't really consider your examples obscure for someone who has knowledge of bash, but using structures (like if statements) that are recognizable to users of other programming languages with no training in bash is also "elegant"
@jeetadityachatterjee6995
@jeetadityachatterjee6995 4 жыл бұрын
When I am writing bash script I usually comment to the point of obsession to make sure anyone new to my script (or bash) has an idea of what code does. It's a bit more work but it makes sure that I get a piece of concise code while also makeing sure people understand what is happening
@robrick9361
@robrick9361 3 жыл бұрын
@@alexandrep4913 Unless that junior programmer was explicitly hired to write Bash scripts, your reasoning is self-centered and dangerous. If you don't help them, they'll go online to find an answer. Which may not be how you want things done resulting in you helping them anyway but with a lot of time wasted in between. Also your argument about code not being around shows a total lack of real world experience. Plenty of corporations have code written DECADES ago still running somewhere in their organization.
@ChrisCox-wv7oo
@ChrisCox-wv7oo 2 жыл бұрын
@@alexandrep4913 lol wut? 😆 you think some one comes and removes your code after you leave a company? that shit is sticking around until it breaks, and then the person who has to work on it benefits greatly if you have written expressive code
@geoffl
@geoffl 2 жыл бұрын
this.. there's basically no cost to using 3 lines for an if over 1 but there's a huge reward that java/python/javascript developers can pattern match a bash if against what they're used to
@ChrisCox-wv7oo
@ChrisCox-wv7oo 2 жыл бұрын
@Evan John Programming ¯\_(ツ)_/¯
@kashnomo
@kashnomo 4 жыл бұрын
It's worth noting that Luke uses these compact forms in a way that makes his code more legible.
@homelessrobot
@homelessrobot 4 жыл бұрын
which is generally harder to do than making the code more legible with control flow statements for people unfamiliar with 'points free'/stream oriented programming. You pick your battles. If most of the code you are writing is bash scripts, its worth focusing on. If not, you are going to waste a lot of time 'mode switching' into stream-centric/points free programming style.
@protoketer4554
@protoketer4554 2 жыл бұрын
yup, the code example he showed was much easier to read than the large if-blocks that I have been guilty of writing lol
@DimitriSabadie
@DimitriSabadie 4 жыл бұрын
I hope people don’t listen to this too seriously.
@m0gria
@m0gria 4 жыл бұрын
One more thing: The following does *not equal* to an if else: condition && statement1 || statement2 because if the condition is true and the statement1 fails statement2 will be executed as well!
@incrediblygay
@incrediblygay 2 жыл бұрын
So, only statements should be used when doing this?
@erdanxiloscient3666
@erdanxiloscient3666 2 жыл бұрын
grouping stuff together should fix that though. Not sure about the shell syntax, but I’m guessing it would be something like: [ condition && statement1 ] || statement2 or $( condition && statement1 ) || statement2 where what’s logically happening is condition fails, which makes statement1 get skipped because of &&, which triggers statement2 to be executed because of ||. Again, I’m not sure so please correct if wrong
@Semaley
@Semaley 3 ай бұрын
Actually, it "may" execute the || or else, but only when the last command executes. Inside curly brackets, you can have non-zero exits, so long as your final command exits 0. In that case, curly braces allow you to use % to find the end of your "if/else", rather than sorting through several layers of if/fi, which is the further issue of over using else. Conditionals should be used to reduce indentation, not evil.
@flarone
@flarone 4 жыл бұрын
Neat info. Definitely some next level bash for 90% of circumstances. Good to see you back at it, Luke.
@m0gria
@m0gria 4 жыл бұрын
If you use set -e in your script the script will fail if any of the commands fail, so you don't need to type && all the time. I set it in most scripts. Then where is set -u as well. This is really helpful, as the script immediately fails if it encounters an undefined variable. This will also disarm bombs such as rm -r "$DIR/$SUBDIR", if one of these variables is not set.
@countdigi
@countdigi 9 ай бұрын
Good point - for the second example, if I ever do a rm command with a variable followed by a slash "/" I use parameter expansion with a dummy name to protect against an unset variable causing the path to start from the root directory (not that I _ever_ had this happen in one of my production scripts ;-). /bin/rm -r "${DIR:-NULL}/$SUBDIR"
@PacAnimal
@PacAnimal 4 жыл бұрын
Yeah, yeah, you can cut down on everything and make oneliners. If you write code like this at work, I will punch you. Write easily readable code, so it's easy to spot your damn bug.
@danteuk8024
@danteuk8024 4 жыл бұрын
Yep everyone in a programming team should dumb their code down to the level of the weakest programmer - or better still the manager that thinks he can code - that way you'll get perfect, easy to read, bug free code. Of course you'll have a million lines of code, that takes a tonne of memory and runs like dog, but, ya - you can work for Microsoft :)
@PacAnimal
@PacAnimal 4 жыл бұрын
@@danteuk8024 It's not about dumbing it down, it's about making clearly readable code. Think the Linux kernel, not stack overflow perl one liners. I thought it was obvious, but I hope this clarified it for you. If statements don't use more memory than chained commands, and if you're conserned about the memory usage of bash itself in your script, you're using the wrong damn language, probably due to your fear of learning about the right tool for the job. If you write all your shit on one line, relying heavily on operator precedence, assumptions and clever tricks, you're making an unmaintainable mess. I have no need for a mess.
@Monk-E
@Monk-E 4 жыл бұрын
@@danteuk8024 That's not how it works...
@peterbonnema8913
@peterbonnema8913 4 жыл бұрын
This is how to not write an if when you actually mean 'if'. How is not writing what you mean improving readability? Also, your example is not so much about the if-statement as it is about errorhandling. But if you are doing a video about errorhandling, then do it properly and talk about signal traps and all that kind of stuff.
@landro3552
@landro3552 4 жыл бұрын
I think the purpose for this is cleaner and more sustainable code
@shire7949
@shire7949 4 жыл бұрын
shut up man, if anything is useless here it's your comment. Tell me, what did you bring to the table that provided anything? I know the video gave me something, who cares about exactness. it's about getting better
@electric26
@electric26 4 жыл бұрын
Shire Grin “it’s about getting better” exactly. He was pointing out how Luke could have done better. And your comment was the only one that didn’t bring something to the table. Not to mention you were being very rude.
@shire7949
@shire7949 4 жыл бұрын
First, we don't know how Luke handles all these comments. If comments like this one discourage him from uploading more, which are FOR FREE by the way, then I would rather stop seeing comments like the above one, than his videos. I don't care if in your mind that comment was helpful. Second, by the same reason it is free, I don't think you get to tell Luke how he should make his videos, or anything at all. It's not fair when you are NOT creating or providing anything. And fuck u if you think I was rude rather than the unthankful guy above, you guys are trash
@electric26
@electric26 4 жыл бұрын
Shire Grin I haven’t heard him say it, but from what I know about him I think he’d welcome constructive criticism, which is what the original comment was. I agree that he can upload whatever he wants, and can choose to ignore what the viewers want if he so desires, but that much is obvious. “And fuck u if you think I’m being rude...you guys are trash” oh, the irony.
@y00t00b3r
@y00t00b3r Ай бұрын
oh my god, I'm bowled over by Luke's discovery of the statement terminator token.
@davocc2405
@davocc2405 3 жыл бұрын
Sorry about the reply on an old video - I think it's worth adding to this that functions can use the RETURN command to return an error level value (e.g. 0, 1, etc.) based on outcome which can be combined in this manner to produce a cleaner main body structure within the main script. It lets you homogenise (and potentially re-use) those segments a bit more too; perhaps even going so far as to offload those tests to another shared script and use the SOURCE command to re-use them. Not sure if that's considered heresy, I'm just trying this out at the moment.
@SzymonDatko
@SzymonDatko 2 жыл бұрын
OMG please no...! My student sent me this video and I thought this was some April fools story, but the publication date of this video is March 19th... This is exactly how one should *not* write conditionals in Bash and its the source of all the people there calling it a cancer language (or hard/unreadable, to put it more politely). Just don't. There is absolutely no real cost in using 3 simple lines instead of 1-line complex statement, no difference in efficiency, while the benefits of code clearness is priceless for the long term. The fact that the language/tool's flexibility allows one to do something, does not mean one should rely on that.
@nilsirl
@nilsirl 4 жыл бұрын
"[" is a command (it more or less aliases to "test"). So when you do `[ -z "$EDITOR" ] && do_smth`, the if is not technically implicit.
@loarto
@loarto 4 жыл бұрын
Same for me. But did you also know that bash has a builtin help system? help [ gives you some overview, they call it a synonym for test
@fuseteam
@fuseteam 4 жыл бұрын
🤯
@PhilippeCarphin
@PhilippeCarphin 4 жыл бұрын
@@Ultr4noob Me too, I was telling myself why do there need to be spaces at places where you don't expect them to be necessary. When I realized it was a regular old executable that simply required it's last argument to be "]", then it made sense. It also blew my mind.
@loarto
@loarto 3 жыл бұрын
@@techtutorvideos you don't even have to have the ; :D
@josephsmy1994
@josephsmy1994 2 жыл бұрын
interesting
@yash1152
@yash1152 2 жыл бұрын
the difference in this suggested style and if-else is that, in this one, all the statements (actions) are the expressions too (aka conditions). whereas in if-else, the expression is separate than the statement.
@Raatcharch
@Raatcharch 4 жыл бұрын
The videos in your reboot so far have been fantastic.
@0hhtecMusicianTheNotecianHero
@0hhtecMusicianTheNotecianHero 11 ай бұрын
This video really helped me clean up some shell scripts that I have recently made. Thank you brother, and God bless
@berndeckenfels
@berndeckenfels 4 жыл бұрын
; does change its mind if you run with set -e, which you always should. And " mayfail || true" is used to ignore it. Typical problem "cd x ; rm -rf *" can fail horribly. (You can use && instead, but it's additional work to remeber it. Especially if you use no ; but next line). Pro tip for ad-hoc scripts. BTW instead of if/|| you can use default value for variables ${EDITOR:-nano} (or :=)
@JohnMatthew1
@JohnMatthew1 4 ай бұрын
OMG, such a simple explanation about BASH, the semi-colon, which I hate in all languages, but you've explained it so easily.
@kirk0831
@kirk0831 4 жыл бұрын
Nice, I really appreciate you make those simple to novice!! Great work!!
@SimGunther
@SimGunther 4 жыл бұрын
Instructions unclear; ended up with a plan 9 emulator in a bash script.
@nerrufam7105
@nerrufam7105 4 жыл бұрын
🥂, you reminded me of the classic: Instructions unclear, d!ck stuck in fan.
@Pabloparsil
@Pabloparsil 3 жыл бұрын
This was really helpful. I was using xrandr to switch between laptop screen and monitor and the thing is that I only want to turn off one screen *if* the other is succesfully activated. Otherwise I don-t want to turn it off. Perfect use case in my mind.
@bitcointrader8586
@bitcointrader8586 4 жыл бұрын
Been looking to get bit better with my shell scripting this helped a bunch .
@Pray4ragE
@Pray4ragE 2 жыл бұрын
That semicolon saved me! Was using && in the wrong place, thank you.
4 жыл бұрын
This video was actually helpful to me: Now I know to not use "&&" all the time. I used to think that that was required to guarantee that a command only starts after the previous one executes, but actually ";" does that as well. So I'll do exactly the opposite of what you suggested from now on. Because using "&&" actually just tells the console to evaluate a condition and then to not do anything with it. And evaluating that condition has "side effects", which are the actual commands you want to run. That is certainly not intended.
@stnsls
@stnsls 4 жыл бұрын
: ${EDITOR:=nano}
@ba-a-a
@ba-a-a 4 жыл бұрын
And how in the name of fuck is this sorcery called? I'm looking for googleable name.
@bartolomeykant
@bartolomeykant 4 жыл бұрын
But if I export EDITOR="" it will works the same way?
@btschaegg
@btschaegg 4 жыл бұрын
@@ba-a-a www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
@desubakadesu
@desubakadesu 4 жыл бұрын
@@bartolomeykant Yep
@desubakadesu
@desubakadesu 4 жыл бұрын
echo "export EDITOR=nvim" >> ~/.zshrc echo "export EDITOR=nano" >> ~/.zshrc echo "export EDITOR=nvim" >> ~/.bashrc echo "export EDITOR=nano" >> ~/.bashrc
@MarcoDamaceno
@MarcoDamaceno 3 жыл бұрын
Functional programming in shell script has never been so real and possible for me. Thank you! I learn a lot from you.
@JKhalaf
@JKhalaf 4 жыл бұрын
This was really nice and enlightening. Thank you.
@antonlee0
@antonlee0 4 жыл бұрын
I want more of this. Thanks for sharing the wisdom.
@con-f-use
@con-f-use 4 жыл бұрын
It's actually bad form, what you do, Luke. At least in scripts that are supposed to be highly reliable and re-usable. In such scripts you would set `set -o errexit -o nounset -o pipefail -o noclobber` or something like that. So error codes of 0 are always errors that kill the script and variables must be set when used. With those stricter options set `[ -z "$EDITOR" ] && EDITOR="nano"` is an error, if there if EDITOR is unset. Twice over actually, because of `nounset` AND because a zero exit-code is not caught (the result of the square brackets). An here if-statement would not "trigger" the `errexit`, though it would still the `nounset`. So stricter scripts, youd either do: ``` [ -z "$EDITOR" ] && EDITOR="nano" || true ``` or use an if statement. Also, you should wrap your actual code in a function (I often call it main) and invoke that function only when the script is run directly. ``` main() { # your code goes here... } if [ "$0" = "$BASH_SOURCE" ]; then set -o errexit -o nounset -o pipefail -o noclobber main "$@" fi ``` That way people can source your script and use the function without accidentally running the script or setting those stricter options. YES, it is boiler plate but it makes bash scripts more reliable and more re-usable.
@JonathanNelson-nelsonj3
@JonathanNelson-nelsonj3 11 күн бұрын
These are great IF you need a single line command. However, when writing an application in Bash please use the expanded syntax as they are easier to read and understand.
@alexanderelgert6037
@alexanderelgert6037 Жыл бұрын
$ echo ${EDITOR:-nano} ${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
@philpeko1796
@philpeko1796 Жыл бұрын
I was going to mention it too, thanks. Yeah, echo ${EDITOR:=nano}, or some other parameter expansion possibility, ${EDITOR:-nano} etc. That Luke Smith does not know the shell in-depths... just "man bash" and Read The Fantastic Manual, @Luke Smith, please
@zcalex7660
@zcalex7660 4 жыл бұрын
I just jumped to a WM next up is to learn some bash scripting for fun so thanks for the new videos.
@nicholasgulachek8421
@nicholasgulachek8421 4 жыл бұрын
This reminded me of a cool bash language feature I just learned when writing a script at work today! $ [ -z $EDITOR ] && EDITOR=nano ; echo $EDITOR ...Can become $ echo ${EDITOR:=nano} Check out the "Parameter Expansion" section in the bash man page. ${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way. There are a bunch of cool features here!
@kaihendry
@kaihendry 4 жыл бұрын
I’m a `if test` kinda guy 😂 .. it looks better to me.
4 жыл бұрын
Generally, me too, for simple things. However, like in Luke's last example, where you have a chain of half a dozen commands, each running depending on whether the previous one was successful, nesting if statements becomes really messy and it looks horrible. Especially having fi fi fi fi fi fi in the end. Yuck.
@shirgar4390
@shirgar4390 4 жыл бұрын
Yeah. These tutorials are interesting and good for beginners I guess, but the code produced wouldn’t pass a code review in a real software engineering firm
@CottidaeSEA
@CottidaeSEA 4 жыл бұрын
@ I saw something about getting the exit code from the previous command. So a way to prevent it would be to store that value and checking if 0. This way you'd avoid nested if statements and they would instead be linear. I'm unsure if it's a realistic approach as I don't actually use this language, I just stumbled upon it, but I see no reason as to why it wouldn't work as long as you write it correctly.
@daggawagga
@daggawagga 4 жыл бұрын
The ] is a lie
@v0ldelord
@v0ldelord 4 жыл бұрын
I think the use of logical operators instead of "if" statements makes sense when working in a terminal. In a bash script I want others (and future me) to understand the code on first glance, an if statement inherently does this because it is the de facto way of controlling flow in most languages.
@Kor1134
@Kor1134 2 жыл бұрын
Looks clean to me. I write my scripts like this, _"if/then/else/fi"_ and _"command && {…} || {…}"_ look functionally identical to me.
@overclucker
@overclucker 4 ай бұрын
I use nested if more often these days. I think it more clearly describes my intent and makes revisiting older scripts easier.
@dr.mikeybee
@dr.mikeybee 4 жыл бұрын
the & character puts the job in the background. The number before the process id is the job number. fg 1 would bring it back into the foreground. jobs will list background jobs and their job numbers. Cntrl z will put a running job into the background, and kill %1 will kill job #1, etc.
@edvonrattlehead2135
@edvonrattlehead2135 4 жыл бұрын
I really needed this video, time to optimize sum scripts, also in what kinda situtations you DO actually need to use the if statement
@apolloapostolos5127
@apolloapostolos5127 Жыл бұрын
I’ve been up to 3 in the morning losing track of my scripts. This helps keep it simple!!! 🎉🎉
@damirahman
@damirahman 4 жыл бұрын
less readable and fewer keywords =/= elegant
@GlebEagle
@GlebEagle Жыл бұрын
Thank you! Was very useful!
@metasavagex
@metasavagex 4 жыл бұрын
I love your videos, thank you so much for making amaaazing terminal videos
@zss123456789
@zss123456789 4 жыл бұрын
I only do casual bash scripting, so this is completely new information, thanks and happily subscribed! The recommended approach here almost sounds like nested try catch blocks, which is pretty neat. (try this. Pass? try next. Pass? try next. Fail. Enter catch block through || and stop trying) Will you cover how you would handle user inputs, or have you covered that already?
@pnddesign
@pnddesign 4 жыл бұрын
Thank you Luke !
@loarto
@loarto 4 жыл бұрын
; is denotes the end of a commond, & denotes the end of a command and backgrounds it, unless it is in an arithmetic expansion where it is bitwise and. && and || are logical operators, but you forgot !, which negates a value. Can test like ! true && echo hello || echo foobar.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 4 жыл бұрын
Do you get the feeling that Bash syntax has, shall we say, evolved by accretion over time? ;)
@nekomantia
@nekomantia 2 жыл бұрын
Thank you for that video && especially for the last example cause logical operators really can do very special thing
@user-mr8ij8gi7c
@user-mr8ij8gi7c Жыл бұрын
To check if $VAR is unset, and give it a default value like <a href="#" class="seekto" data-time="660">11:00</a> on video, the bourne Shell has had syntax ${VAR:=default} for over 30 years... though I know you were trying to focus on if/else style logic. Clear readable, and reliable code is still preferred, which ever syntax is used.
@DennisChaves
@DennisChaves 4 жыл бұрын
blowin' my mind again. Great video!
@dragangolic6515
@dragangolic6515 2 жыл бұрын
Great videos, I learn a lot about bash and Linux from you. Thank you
@lemler3337
@lemler3337 4 жыл бұрын
wow this is super useful, even to a bloat user like myself! thanks
@PianoShawn
@PianoShawn 7 ай бұрын
Thx man, very helpful information
@KipIngram
@KipIngram 2 ай бұрын
I don't regard if/then as "ugly," but there's no denying the && || approach is better.
@drewberchtolzthofen886
@drewberchtolzthofen886 Жыл бұрын
Beautiful explanation, Luke!
@jasons1856
@jasons1856 4 жыл бұрын
Thanks again. Huge help!
@windowsrefund
@windowsrefund 4 жыл бұрын
Power move: your echo statements really don't need to be quoted. Sweet!
@waseemqaffaf5715
@waseemqaffaf5715 Жыл бұрын
RESPECT!! AMAZING VIDEO GONNA START DOING THIS
@CarloPiana
@CarloPiana 4 жыл бұрын
That would have made many of my dumb scripts easier to write. Thanks, good teaching there!
@musclesmouse
@musclesmouse 4 жыл бұрын
Thanks, I have always wondered how some of these complex scripts meant. I only have been doing file manipulation using grep.
@mc4ndr3
@mc4ndr3 12 күн бұрын
IF encourages fragile, inflexible, overly specialized programs(any programming language). IF reduces performance. IF exhibits a maintenance problem that grows exponentially, doubling and redoubling the program state space. Rather, think in terms of full case/switch statements. Inform your data models so that they naturally flow each of the different possible input values and program states into an intuitive, useful state.
@Linuxdirk
@Linuxdirk Жыл бұрын
Reminds me of the guy who said "don't nest your code" and then chained half a dozen functions together by assigning the result to available and giving this variable to the next function.
@ensomniac
@ensomniac 2 ай бұрын
Elegance is readability. If statements are almost always more readable to more engineers than the things you suggest here.
@rodrigosouto9502
@rodrigosouto9502 3 жыл бұрын
I'm with Luke on this one.
@sergeynaruzhiny7422
@sergeynaruzhiny7422 3 жыл бұрын
awesome guide, you explained it good, Thanks A lot
@jackoberto01
@jackoberto01 4 жыл бұрын
I have no idea what a bash script but I knew about all of the logical operators from use in if statements ironically
@wesg01
@wesg01 3 жыл бұрын
Very nice. Thanks!
@MatthewDeVore
@MatthewDeVore 4 жыл бұрын
EDIT: I used to think foo && bar would terminate the script in set -e mode if "foo" fails and wrote a comment to that effect. Apparently, not so. Sorry for the confusion. I still prefer to use the "if" statement but that's mostly a stylistic preference at this point. It at least lets you add more lines in the body of the if statement later on without making your VCS diff noisy.
@MatthewDeVore
@MatthewDeVore 4 жыл бұрын
@ Actually, looks like I was wrong about this. foo && bar won't terminate the script if "foo" fails in set -e mode. Sorry!
@PhilippeCarphin
@PhilippeCarphin 4 жыл бұрын
I have a story for you Consider this scritp: # warn_if_file_@t [ -e some_file ] && echo "warning, this file exists but shouldn't" If the file doesn't exist, this the script itself will exit with non-zero exit status. A script like this is used in my profile at work because it is part of a weird environment setup thing that everyone has to use. When we started doing CI with gitlab, we didn't know that it activates the equivalent of set -o errexit for the jobs it runs. Our environment setup made it up to the warnings script and crashed. When trying to hunt down the reason for the failure, we investigated the environment setup by doing part of it, then adding a bit more until we got the crash. My supervisor and I were investigating this together. When we got to this warn_if_file_exits.sh, we were going to add just that, but looking at what it did, we were both convinced that this script couldn't be the reason, so we added that and a bunch of other stuff, then we got the crash. So we had narrowed it down but the day was over so we went home. The next day, I went back over what we did more methodically and found that it was that leaked test. Lesson learned: Never write ifs like that.
@MatthewDeVore
@MatthewDeVore 4 жыл бұрын
​@@PhilippeCarphin Oh, that's a good point. So even though `foo && bar` won't terminate the script for a failing `foo`, it will set the exit status if it's the last line of a script or function.
@PhilippeCarphin
@PhilippeCarphin 4 жыл бұрын
@@MatthewDeVore One of the lesser known "features" of Bash.
@MatthewDeVore
@MatthewDeVore 2 жыл бұрын
@@anonymousalexander6005 I didn't know that || exit will propagate an exit code. Thank you for the tip. I've been preferring the abbreviated style suggested by Luke lately. I tend to be against verbosity in coding style. I found over time that 90% of my conditionals in shell scripting were covered by the `foo || bar` and `foo && bar` patterns. I'd rather not make something verbose and ceremonial "just in case" I may refactor it later and I want the diff to look nice.
@neonblood4658
@neonblood4658 4 жыл бұрын
The quarantine isn't all too bad if we get a Luke vid everyday
@Filaxsan
@Filaxsan 4 жыл бұрын
Very useful info, Luke
@kychemclass5850
@kychemclass5850 2 жыл бұрын
Tq. I appreciate the knowledge.
@a_maxed_out_handle_of_30_chars
@a_maxed_out_handle_of_30_chars 4 жыл бұрын
Corona-chan is helping me learn bash script :)
@zvezdan956
@zvezdan956 3 жыл бұрын
@@robertkiestov3734 Unironically true and based.
@gayusschwulius8490
@gayusschwulius8490 3 жыл бұрын
@@robertkiestov3734 The "pandemic" is a real illness (I had it), but it isn't nearly dangerous enough to justify all the measures that have been taken to avoid it. It's essentially just a glorified flu. Yeah, you feel like shit for a few days, with coughing, fever etc., but it really isn't worse than just getting regular flu. Even 74 yo Trump survived it without a problem.
@eduardoantunes2958
@eduardoantunes2958 3 жыл бұрын
@@gayusschwulius8490 I don't know man. One of my dad's best friends died yesterday. My dad's 54 years old, and his friend was just a couple of years younger. Didn't have any severe health problems or anything. Some weeks ago another friend of his also died. Same story. I've just never seen the flu kill people like that. On the other hand, I live in Brazil, and here there have been some new variants of the virus that kill younger people. Maybe in US only older and more immunologically fragile people die, but still, judging by the death count there I'm pretty sure it's more lethal than the flu.
@drygordspellweaver8761
@drygordspellweaver8761 3 жыл бұрын
More people have died of the “vaccine” than the virtual coof.
@zvezdan956
@zvezdan956 3 жыл бұрын
@@gayusschwulius8490 just because u had a cough doesnt prove the existence of a pandemic. u r brainwashed, seriously.
@maxrandom569
@maxrandom569 4 жыл бұрын
that's just purest art
@johseh5312
@johseh5312 Жыл бұрын
Great stuff. I am baffled by a lot of the criticism I see here in the comments. I hate being expected to learn to write lengthy, bulky and usually just ugly code for the excuse of "readability". I'm very much a beginner coder, but always look for ways of writing less code that is also clearer, which what is being shown in this video simply is to me. It appears to me that many people have simply decided that writing more lines of code using as many human-language words as possible by definition makes things more readable. It might be sometimes, but it clearly isn't always according to some of us. Dogmatic thinking still rules the minds of many, whatever the subject matter, I will submit. There might be two major categories of coders with regards to this issue, or perhaps context simply matters once again.
@wjckc79
@wjckc79 3 жыл бұрын
15 minutes of better than any of my books on $BASH
@cheesits456
@cheesits456 3 жыл бұрын
If you want to split code across multiple lines instead of using a semicolon between each command, you can do something like condition && { command1 command2 . . . } || { command3 command4 . . . }
@samgould8567
@samgould8567 2 жыл бұрын
This has the added effect that the second block will run if the first block fails. For example, try the following: true && false || echo foo # "foo" will be echoed. Sometimes this behavior is desired, sometimes not
@vilks_jan
@vilks_jan 4 жыл бұрын
Good stuff! Thank you
@zbiqu23
@zbiqu23 4 жыл бұрын
awseome, thanks for that!
@boori9557
@boori9557 2 жыл бұрын
Luke, I wish I can be as confident as you.
@Kor1134
@Kor1134 2 жыл бұрын
I wrote a bash script with bitwise flags using arithmetic logic gates in this fashion, so if a specific bit was set to 1 in the flags variable, a certain process would be carried out. Looked like this: _(( FLAGS & FLAG_NAME )) && {_ _COMMAND_LIST_ _}_ or if a flag bit is set to 0: _(( ~ FLAGS & FLAG_NAME )) && {_ _COMMAND_LIST_ _}_
@Kor1134
@Kor1134 2 жыл бұрын
@Terminalforlife (LL) oops! Yeah, supposed to be braces, not parentheses. I used to use _If_ statements for all my conditional statements, until I realized I can shorthand them by just using the _[ condition ] && {...} || {...}_ syntax. After all, that's what this video is all about, but there are scenarios where an _If_ statement can't be avoided.
@letspartie
@letspartie 4 жыл бұрын
pipefail in bash also helps reducing if, ands.
@hersenbeuker
@hersenbeuker 4 жыл бұрын
ED IS THE STANDARD TEXT EDITOR
@readmelast
@readmelast 4 жыл бұрын
cat is the standard text editor! :-p
@andrasfogarasi5014
@andrasfogarasi5014 4 жыл бұрын
yeah well you can do this in c++ too it's just that people will hate you for it
@suyuro_
@suyuro_ 4 жыл бұрын
Great tutorials.
@davidrihtarsic2615
@davidrihtarsic2615 3 жыл бұрын
[[ tast ]] && command_1 || command_2 This code can execute BOTH commands in some cases... If "test" is TRUE; the command_1 will execute, but if then the command_1 fails for some reason - also the command_2 will be executed. So... using IF-THEN-ELSE is not a bad idea ... it has a reason.
@johanfer
@johanfer 4 жыл бұрын
Thanks man! I'm really learning a lot with you. I appreciate the time you put into this videos.
@lukaszmajkowski
@lukaszmajkowski 4 жыл бұрын
this changed my world!
@kerbrose
@kerbrose 4 жыл бұрын
This is really amazing
@kokosensei5231
@kokosensei5231 7 күн бұрын
Thank you for share!
@AtomToast
@AtomToast 4 жыл бұрын
note that this works because the brackets are just an alias to the `test` program. Check it's man page for some more info
@BrunoBeltran
@BrunoBeltran 7 ай бұрын
Honestly lots of people complaining about obfuscation, but the #1 thing that would have improved this video for me would have been to mention that logical operators in bash must be enclosed in squiggly brackets to change order of operations! I can already see the hundreds of newbies watching this video all collectively crying as they try to figure out why parentheses aren't working xD
@ertwro
@ertwro 4 жыл бұрын
Sometimes only using operators is better but "if...then...else...fi" is not equivalent to "...&&...||..." In the if statement you wouldn't execute the or command if the first command failed. Although, you could do the same by adding parenthesis and grouping the second and third operation.
@Robert-qw3lr
@Robert-qw3lr 9 күн бұрын
the bash ifs I use are always for checking the input params at the top of a script.
@JethroYSCao
@JethroYSCao 3 жыл бұрын
Can this style be used to easily replace if/elif/else type of conditionals? I guess you can do condition && cmd_true || cmd_false But for one, this looks kind of clunky. And more importantly, this isn't even semantically the same as if/else, because if cmd_true were to fail, then cmd_false would be executed, which doesn't occur in if/else constructs.
@yash1152
@yash1152 2 жыл бұрын
i dont remember what semantically means 😅 but the difference in this suggested style and if-else is that, in this one, all the statements are the expressions (aka conditions). whereas in if-else, the expression is separate than statement.
@wouldbabyhitlerkillyou4217
@wouldbabyhitlerkillyou4217 2 жыл бұрын
Exactly. Bad video, poor guidance for beginners (which clearly this video is intended for). Not only are if/then's more readable, but are also absolutely necessary half of the time because AFAIK sh has no ternary operator (cond ? true : false). If typing is an issue, that's what snippets and/or keyboard shortcuts/mappings are for.
@lukevideckis2260
@lukevideckis2260 Жыл бұрын
if [a] b elif [c] d else e becomes ([a]&&b||true)||([c]&&d||true)||e||true
@docslinux2
@docslinux2 4 жыл бұрын
Thank you
@AnthonyP2A
@AnthonyP2A 2 жыл бұрын
EXCELLENT!!! TY!!!
@zaspanyflegmatyk2446
@zaspanyflegmatyk2446 3 жыл бұрын
this is very very helpful, please fo more!
@xseman
@xseman 4 жыл бұрын
if elegant means "Do as much as possible with as less code as possible", then it's ok, but someone new may be confused by some operations
@Yautjaprime
@Yautjaprime 4 жыл бұрын
Yeah, readability is important too
@michaelgrubb3508
@michaelgrubb3508 4 жыл бұрын
I agree, there are definitely uses for these ideas but the notion that you should never use "if" is ridiculous. In fact there are few circumstances in programming that one should never use.
@paolo_in_corsivo
@paolo_in_corsivo 4 жыл бұрын
test -n "$EDITOR" || EDITOR=nano to me looks more fluent and elegant than [ -z "$EDITOR" ] && EDITOR=nano but I got the point of the video and mostly agree
Looks realistic #tiktok
00:22
Анастасия Тарасова
Рет қаралды 60 МЛН
아이스크림으로 체감되는 요즘 물가
00:16
진영민yeongmin
Рет қаралды 28 МЛН
路飞被小孩吓到了#海贼王#路飞
00:41
路飞与唐舞桐
Рет қаралды 39 МЛН
KINDNESS ALWAYS COME BACK
00:59
dednahype
Рет қаралды 122 МЛН
Became invisible for one day!  #funny #wednesday #memes
00:25
Watch Me
Рет қаралды 52 МЛН
Happy 4th of July 😂
00:12
Pink Shirt Girl
Рет қаралды 35 МЛН
THEY made a RAINBOW M&M 🤩😳 LeoNata family #shorts
00:49
LeoNata Family
Рет қаралды 30 МЛН
Самое Романтичное Видео ❤️
00:16
Глеб Рандалайнен
Рет қаралды 4,3 МЛН
Who has won ?? 😀 #shortvideo #lizzyisaeva
00:24
Lizzy Isaeva
Рет қаралды 10 МЛН
I Can't Believe We Did This...
00:38
Stokes Twins
Рет қаралды 83 МЛН
Did you believe it was real? #tiktok
00:25
Анастасия Тарасова
Рет қаралды 50 МЛН
孩子多的烦恼?#火影忍者 #家庭 #佐助
00:31
火影忍者一家
Рет қаралды 47 МЛН
LOVE LETTER - POPPY PLAYTIME CHAPTER 3 | GH'S ANIMATION
00:15
Incredible magic 🤯✨
00:53
America's Got Talent
Рет қаралды 50 МЛН
🤔Какой Орган самый длинный ? #shorts
00:42
Русалка
01:00
История одного вокалиста
Рет қаралды 2,5 МЛН
Каха и суп
00:39
К-Media
Рет қаралды 1,7 МЛН
A clash of kindness and indifference #shorts
00:17
Fabiosa Best Lifehacks
Рет қаралды 13 МЛН
Я нашел кто меня пранкует!
00:51
Аришнев
Рет қаралды 4 МЛН
ОСКАР vs БАДАБУМЧИК БОЙ!  УВЕЗЛИ на СКОРОЙ!
13:45
Бадабумчик
Рет қаралды 3,7 МЛН
Survival skills: A great idea with duct tape #survival #lifehacks #camping
00:27
HOW DID HE WIN? 😱
00:33
Topper Guild
Рет қаралды 37 МЛН
Nutella bro sis family Challenge 😋
00:31
Mr. Clabik
Рет қаралды 11 МЛН
1❤️
00:17
Nonomen ノノメン
Рет қаралды 13 МЛН
That's how money comes into our family
00:14
Mamasoboliha
Рет қаралды 8 МЛН
Me: Don't cross there's cars coming
00:16
LOL
Рет қаралды 14 МЛН
Heartwarming: Stranger Saves Puppy from Hot Car #shorts
00:22
Fabiosa Best Lifehacks
Рет қаралды 20 МЛН
When You Get Ran Over By A Car...
00:15
Jojo Sim
Рет қаралды 19 МЛН
БОЛЬШОЙ ПЕТУШОК #shorts
00:21
Паша Осадчий
Рет қаралды 9 МЛН
Жайдарман | Туған күн 2024 | Алматы
2:22:55
Jaidarman OFFICIAL / JCI
Рет қаралды 1,7 МЛН
Was ist im Eis versteckt? 🧊 Coole Winter-Gadgets von Amazon
00:37
SMOL German
Рет қаралды 35 МЛН
THE POLICE TAKES ME! feat @PANDAGIRLOFFICIAL #shorts
00:31
PANDA BOI
Рет қаралды 24 МЛН
Вечный ДВИГАТЕЛЬ!⚙️ #shorts
00:27
Гараж 54
Рет қаралды 14 МЛН
THEY WANTED TO TAKE ALL HIS GOODIES 🍫🥤🍟😂
00:17
OKUNJATA
Рет қаралды 20 МЛН
Can You Draw A PERFECTLY Dotted Line?
00:55
Stokes Twins
Рет қаралды 100 МЛН
NERF WAR HEAVY: Drone Battle!
00:30
MacDannyGun
Рет қаралды 51 МЛН
DO YOU HAVE FRIENDS LIKE THIS?
00:17
dednahype
Рет қаралды 81 МЛН
3M❤️ #thankyou #shorts
00:16
ウエスP -Mr Uekusa- Wes-P
Рет қаралды 13 МЛН
I CAN’T BELIEVE I LOST 😱
00:46
Topper Guild
Рет қаралды 101 МЛН
1 or 2?🐄
00:12
Kan Andrey
Рет қаралды 47 МЛН
когда повзрослела // EVA mash
00:40
EVA mash
Рет қаралды 4,1 МЛН
КАРМАНЧИК 2 СЕЗОН 7 СЕРИЯ ФИНАЛ
21:37
Inter Production
Рет қаралды 520 М.
你们会选择哪一辆呢#short #angel #clown
00:20
Super Beauty team
Рет қаралды 22 МЛН
Мы никогда не были так напуганы!
00:15
Аришнев
Рет қаралды 6 МЛН
버블티로 체감되는 요즘 물가
00:16
진영민yeongmin
Рет қаралды 110 МЛН
Smart Sigma Kid #funny #sigma #comedy
00:25
CRAZY GREAPA
Рет қаралды 16 МЛН
Vivaan  Tanya once again pranked Papa 🤣😇🤣
00:10
seema lamba
Рет қаралды 33 МЛН
Khó thế mà cũng làm được || How did the police do that? #shorts
01:00
ОСКАР ИСПОРТИЛ ДЖОНИ ЖИЗНЬ 😢 @lenta_com
01:01
MEGA BOXES ARE BACK!!!
08:53
Brawl Stars
Рет қаралды 36 МЛН
Alat Seru Penolong untuk Mimpi Indah Bayi!
00:31
Let's GLOW! Indonesian
Рет қаралды 15 МЛН
Wait for the last one! 👀
00:28
Josh Horton
Рет қаралды 147 МЛН
The child was abused by the clown#Short #Officer Rabbit #angel
00:55
兔子警官
Рет қаралды 24 МЛН
He sees meat everywhere 😄🥩
00:11
AngLova
Рет қаралды 11 МЛН
ОДИН ДЕНЬ ИЗ ДЕТСТВА❤️ #shorts
00:59
BATEK_OFFICIAL
Рет қаралды 9 МЛН
Дибала против вратаря Легенды
00:33
Mr. Oleynik
Рет қаралды 5 МЛН
Always be more smart #shorts
00:32
Jin and Hattie
Рет қаралды 47 МЛН
Пробую самое сладкое вещество во Вселенной
00:41
Final muy increíble 😱
00:46
Juan De Dios Pantoja 2
Рет қаралды 50 МЛН
I wish I could change THIS fast! 🤣
00:33
America's Got Talent
Рет қаралды 117 МЛН
МАМА И STANDOFF 2 😳 !FAKE GUN! #shorts
00:34
INNA SERG
Рет қаралды 4,7 МЛН
ИРИНА КАЙРАТОВНА - АЙДАХАР (БЕКА) [MV]
02:51
ГОСТ ENTERTAINMENT
Рет қаралды 14 МЛН
ROCK PAPER SCISSOR! (55 MLN SUBS!) feat @PANDAGIRLOFFICIAL #shorts
00:31
🌊Насколько Глубокий Океан ? #shorts
00:42
Children deceived dad #comedy
00:19
yuzvikii_family
Рет қаралды 8 МЛН
Получилось у Вики?😂 #хабибка
00:14
ХАБИБ
Рет қаралды 7 МЛН
OMG🤪 #tiktok #shorts #potapova_blog
00:50
Potapova_blog
Рет қаралды 18 МЛН
Tom & Jerry !! 😂😂
00:59
Tibo InShape
Рет қаралды 67 МЛН
The day of the sea 🌊 🤣❤️ #demariki
00:22
Demariki
Рет қаралды 107 МЛН