by narnianal · 7y ago · 0 comments
Sure, I love python, but if I want to find and filter some files nothing is easier to write than bash, so it's possible to have a quite big bash script even doing a good job and being well readable.
I'm honestly a little shocked that this doesn't seem to be common knowledge anymore and your post got upvoted so high.
My main language is Python btw.
Please don't tell me never to use spaces in file names.
How many human resources are required to track down and fix why a bash script suddenly starts failing mysteriously, years after it was written, when somebody mistakenly dares to use a space in a file name?
That kind of problem never happens with Python scripts (including problems with file names including other punctuation and unicode characters), because Python simply represents file names as strings.
For a scripting language that was indented to manipulate file names all the time, bash sure fucked up big time.
https://www.linuxjournal.com/article/10954
>Work the Shell - Dealing with Spaces in Filenames
>[...] I've outlined three possible solution paths herein: modifying the IFS value, ensuring that you always quote filenames where referenced, and rewriting filenames internally to replace spaces with unlikely character sequences, reversing it on your way out of the script.
>By the way, have you ever tried using the find|xargs pair with filenames that have spaces? It's sufficiently complicated that modern versions of these two commands have special arguments to denote that spaces might appear as part of the filenames: find -print and xargs -0 (and typically, they're not the same flags, but that's another story).
>During the years I've been writing this column, I've more than once tripped up on this particular problem and received e-mail messages from readers sharing how a sample script tosses up its bits when a file with a space in its name appears. They're right.
>My defensive reaction is “dude, don't use spaces in filenames”, but that's not really a good long-term solution, is it?
>What I'd like to do instead is open this up for discussion on the Linux Journal discussion boards: how do you solve this problem within your scripts? Or, do you just religiously avoid using spaces in your filenames?
>Dave Taylor has been hacking shell scripts for a really long time, 30 years. He's the author of the popular Wicked Cool Shell Scripts and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
(Dave wrote that 8 years ago, and there are still zero comments on it. Nobody has a good solution! Bash is just permanently fucked when it comes to file names.)
#!/bin/bash
# run this scri0t with 0 or more filename args
for file in "$@" ; do
do_something_with "${filename}"
done
> Nobody has a good solution! Bash is just permanently fucked when it comes to file nameFrom the man page bash(1):
Special Parameters
@ Expands to the positional parameters, starting from one.
When the expansion occurs within double quotes,
each parameter expands to a separate word.
That is, "$@" is equivalent to "$1" "$2" ...Most people don't test their bash on spaces. Look at the dismissive commenter above who just things "nah why would people use spaces in filenames?". Do you think he quotes everything properly? No chance.
CMake is also really bad about this. Although it is arguable slightly better because it uses semicolons as list delimiters instead of spaces, and semicolons in filenames are going to be very uncommon. I would expect there isn't a single CMake project out there that works if you build it in a path containing a semicolon though!
The same kind of lazy care-free people who love the convenience of PHP's "register_globals", because it "saves typing".
If they're too lazy to use something like Python in the first place, they're probably also too lazy to be conscientious and anal retentive enough to write and test bash scripts that handle spaces in file names properly, or do any kind of user input sanitization.
And they don't think twice about running their scripts as root, either. Or writing blog postings telling other people to copy and paste their code snippets into a root shell, or worse yet download and run them without auditing first, by piping curl into a root shell.
I recently had an Xcode project fail to build (blender, which uses cmake), because I was using a version of Xcode that had a space in its directory name (because I had foolishly added a space followed by the version number to the name "Xcode 9.4.1.app"). Of course that was because of some of the tools and custom build steps were calling out to bash. The problem wasn't in any of the source code or configuration files, it was in the file name of the tool itself! It took hours of frustration poring over machine generated project and makefiles to diagnose the problem from the obscure unhelpful error message, which I will never get back.
In the long term, isn't it more efficient of a lazy person's time to simply use a scripting language that just doesn't have these problems in the first place, and doesn't require you to preemptively bend over backwards and dodge silent invisible bullets all the time?
It's pretty ridiculous that a scripting language intended to be used to operate on files falls flat on its face and is so difficult to use when you have something as common and innocuous as files with spaces in their names (or worse yet, file names that begin with dashes -- think of the security implications of that: not something a lazy careless bash scripter would ever pause to reflect about)!
It really is an extremely common and unsolved problem. Notice how each "better answer" is actually worse than the last and comes with its own host of problems and edge cases and work-arounds:
https://unix.stackexchange.com/questions/9496/looping-throug...
https://stackoverflow.com/questions/3967707/file-names-with-...
https://www.cyberciti.biz/tips/handling-filenames-with-space...
https://www.tecmint.com/manage-linux-filenames-with-special-...
https://www.hecticgeek.com/2014/02/spaces-file-names-command...
$ find . -type f
./foo bar
./--stupid-filename
./-annoying dir name!/--very annoying path...
$ echo "pid=$$"
pid=31281
$ while IFS= read -r -d '' file ; do
> echo "[pid=$$] do something with '${file}'"
> list[i++]="$file"
> done < <(find . -type f -print0)
[pid=31281] do something with './foo bar'
[pid=31281] do something with './--stupid-filename'
[pid=31281] do something with './-annoying dir name!/--very annoying path...'
$ declare -p list
declare -a list='([0]="./foo bar" [1]="./--stupid-filename" \
[2]="./-annoying dir name!/--very annoying path..." [3]="./iter.sh")'
Using the character literal $'\0' also works as the delimiter, but Bash doesn't support sending null bytes in args. In bash, $'\0' is the empty string: $ x=$'\0'
$ declare -p x
declare -- x=""And good for them! What kind of savage puts spaces on their filenames?
https://en.wikipedia.org/wiki/Whitespace_(programming_langua...
I also use spaces in the file names of all my C++2000 source code that takes advantage of the wonderful new whitespace overloading feature -- it's conventional to use the ".cpp " and ".h " suffixes with trailing spaces.
Now that the modern compilers and interpreters (clang, python3, etc) allow unicode in variable names, the next step is certainly to accept spaces in variable names. With a slight modification, the python language can be adapted to support spaces inside variable names.
After all, people have the right to name their variables however they want!
In any case I don't say put in a Bash script and let it grow to ten million lines over 20 years.
My approach to bash scripts is this:
1. start with a bash script to understand a problem and see how a solution might be structured. PoC level is enough here.
2. When you know you solve the right problem and the customer is willing to make something bigger, then put ~80% of the code in a good programming language (Python is my personal favorite, but Ruby, Java, PHP, C#, C++, Lisp might also work). That happens about 3 months into a project.
3. If you start to hit bottlenecks and performance ceilings put the 30-50% that are relatively stable and most performance hungry into C/C++ code and really optimize the heck out of it. This should be done only with an aged project, like 2 years in, and very pessimistically, since highly optimal code usually is badly readable and badly maintainable. You certainly don't want to go into that code 6 years later and drastically change its API to your python code.
So a ten year project would have a thin layer of bash/docker at the top, a strong core of highly flexible code (of Python for me as well) in the middle, and a leg of high performance C code here and there.
I honestly have never seen a project that really needed the C-layer though. In modern IT world it seems most problems are old at least from a political/management point of view between 2 weeks and 3 months. So in fact, although I count myself as a Python coder, the last few years I've spent writing way more bash and docker related stuff, which then is either never touched again or directly thrown away after a few weeks, no matter if successful or not.
PS: Please don't use spaces in file names. Not just for scripts. It is also not clear for users where something ends, and they are even less used to putting string indicators around file names than you are about handling spaces with bash there.
And last but not least stuff like spaces in filenames, starting scripts with upper case letter etc, they might even be just a small annoyance. But you can be sure that skilled developers will put you 2 classes below their average when they see this, because it simply shows a lack of the right spirit.
I do agree though that filesystems are not the most user friendly abstraction of data. Maybe we can do better than that.
But also filesystems have the huge advantage that they are somewhat user friendly while also being somewhat technology friendly. Therefore I'm also not too mad about their existence. There are a lot of end user problems that can be solved quickly exactly because they just need a professional one time query and FS+bash+clis are such a good combo to craft that query.
This is not true, and I do not see why it should be like that. You cannot, for example, have slashes in filenames; and for good reasons. Disallowing spaces in filenames solves a lot of problems.
For simpler, more expressive Python system scripts use Plumbum: https://plumbum.readthedocs.io/
> but if I want to find and filter some files nothing is easier to write than bash
That's like 10 lines in Python and much easier to read and test.
Look. We are working an professional field with a strong scientific foundation. There is no "this bridge is harder to drive over for me therefore I think it's bad architecture". The easiness and expressiveness depend on the problem you try to solve, not on the people, their tastes or their experience.
Shell tools are highly optimized to work in pipes, to work on files and to work on line separated entries like lines of code or lines of CSV. So if you have a problem where you need to pipe file handling into some filtering and into some line based transformations then you will have a hard time to find anything as easy or expressive as a bash script. And most projects on a unix-like operating system at least start like this: Understand the problem based on database dumps, logs, csv data measurements, previously written code etc.
If your regular expressions are not able to cover all the edge cases anymore and/or become unreadably complex then of course you should start an actual program. That only happens a few weeks into most topics though.
> doubly so when you need to throw more of them at this thing written by a former developer that thought he or she was saving money for the org by not spending an extra 30 minutes writing the program in Python or Go.
Yes, there are people who lack the skill or ambition to develop good code. We all hate when we need to deal with their stuff. But honestly, would they have written better code if they had used Python or Java or C++ for that problem? Unlikely.
A good coder would have some feeling for when he outsources some functionality to a python script. And if he develops a code base for a longer time most of his code will be in a real programming language. But even then it might be wrapped into a thin layer of bash to use find or grep or something that cleans up the input a little.
It's a single command in bash, invoking a program far more efficient than anything you can put together in python. It is literally a tool written for this exact purpose. I think it is simply ridiculous to not use a pre-existing tool that frankly you cannot out-do with a scripting language.
Even if you are writing a python script, you should _still_ use find to search for files if there is _any_ complexity in the search requirements.