Or you can just…not quote the tilde. Folks always seem to reflexively quote “strings” in Bash while not realizing that (almost) everything is a string and most strings are not quoted and it would be odd to do it (e.g. no one is doing `"ls" "-a" "foo"`).
Also in general your advice is very bad advice. In command-line arguments, which is the vast majority of the code of any shell script, you should always quote strings that contain variable expansion unless you want them to be implicitly split on spaces after variable expansion, because the thing you're storing in the variable is not an atomic string but rather a space-separated list.
This is almost never what you actually want, and in the rare cases that you do want to store a list, the shell's implicit space splitting usually breaks on filenames containing spaces. Bash has actual array variables which make it possible, but horrible, to handle this in a first-class way:
: tmp; x=("foo bar" baz)
: tmp; echo "${x[@]}"
foo bar baz
: tmp; touch "${x[@]}"
: tmp; ls -l "${x[@]}"
-rw-r--r-- 1 user user 0 Oct 11 17:52 baz
-rw-r--r-- 1 user user 0 Oct 11 17:52 'foo bar'
This feature is absent in the Bourne shell and in dash.
In general, whenever you see a $variable $expansion in a shell script outside of double quotes, you should suspect that the shell script will probably fail if your filenames or directory names contain spaces. In very many cases, this results in path injection security vulnerabilities. There are contexts where unquoted $variable $expansion is safe, but they are relatively rare.
Almost nobody that I've ever worked with knows how the shell works. I send them [the docs][1] but what kind of world would this be if people read the docs? Also, not exactly a page turner.
I learned this stuff from friends, O'Reilly books and endless nights of failure and trial and error. I'm certainly not a super wizard, but I feel like I'm not missing any shell skills to be able to do what I need to do.
[Insert mild rant on kids these days having no attention span any more]
This feature, or at least the syntactic unit in question has a name here "bare words". You also have these in some contexts in Perl and Ruby, YAML, and probably some other languages, idk.
I've also seen this even with people who seem like generally competent shell users. Idrgi
Unless you're running a shell command from python. That was the first time I saw a command string broken down into "string" arguments for every thing like that.
In that case, you're not running a "shell command" from python, you're passing arguments to exec. A shell command would be a string interpreted by the shell, and you'd use that for shell syntax things like having the shell do variable interpolation or redirections as part of executing the command.
I don't use WYSIWYG editors anymore, so I have to remind myself to use those when writing raw HTML text. Although, most browsers correct raw ' and " symbols in text now, I still try to use them to have compliant HTML
They are typographically the right thing to have been using all along.
Using ' and " to pretend to be ‘/’ or “/” is on par with the typewriter days where people would use the l key to stand in for 1 also. A justifiable approximation when technology limitations prevented using the real deal, but an approximation all the same.
In fact, if we had been using left and right quotes from the beginning in shells, most “quoting problems” go away, as they’re all inherently rooted in not being able to know what level of nesting a quote character is at.
m4 did in fact use left and right quotes from the beginning, but it still had other quoting problems. Really terrible ones, to the point of making the language unusably bug-prone for anything beyond very basic tasks, which is why it's mostly forgotten.
' can be feet (of measure) or arcminutes from cartography.
These actually all have slightly different symbols, and the symbols for the left/right quotation marks are actually farthest from this approximation, even if they are the most frequent usage.
It’s always been wrong in some respect to use a single available symbol to emulate three or more different typographical tasks, but quotation marks may actually be the one where the emulation is the most wrong.
I used to put it first for convenience, but got increasingly paranoid about something same-named getting slipped into my ~/.local/bin; now it lives at the end.
The Z shell's, C shell's, and others's syntaxes for setting the PATH environment variable via a shell array variable alias also does the tilde expansion.
path=( $path ~/bin )
It's worth noting, also, that the path and manpath settings in login.conf(5) expand leading tildes in individual search path items.
Oh, you mean bash specifically. Then yeah, that's reasonable enough. Although I agree with the other commenter that sh/bash have the advantage of ubiquity.
None of those have the #1 best thing bash is good at: bash is already installed, nushell and fish are not.
Powershell is, as I understand it, not available on Linux but is omnipresent on Windows, so hopefully the windows folks can use it like they would bash.
PowerShell works on Windows because of WMI, to a first approximation.
Because Windows is tied together through APIs and databases and not text files (unlike Linux), everything is text is not as useful as something that can talk objects. And a lot of Windows is object oriented, from the window message dispatching system through COM and down to NT's object manager.
Ruby replaced all my shell needs. Almost 25 years ago.
I even have a shell written in ruby (it handles both
bash-like behaviour as well as ruby code as-is); admittedly
it is not quite perfect for everything, but I improve on
it steadily. And it works on Windows too, which was one
reason I wrote it in the first place (need to have it work
via cmd.exe as-is).
Never looked back to shell. It is too awful to use.
That’s not correct because POSIX passes what is ostensibly an array of strings.
Windows, on the other hand, only passes one string. So it’s up to the application to choose how to handle whitespace, quotation marks, and other nuances with parsing parameters.
Variable expansion in Bash is lazy. But there’s no reason why variables cannot be tokenised so that strings with spaces aren’t treated as multiple parameters. And in fact that’s exactly how some other shells work, such as the one I maintain.
While unix handles splitting into an array of strings, it still leaves parsing those strings up to the application. One of the bigger problems is the ambiguity caused by filenames starting with `-`. Some applications support the `--` marker to end such parsing, but it's inconsistently implemented and the caller has to actively remember to use it.
A typed array (e.g. by having a required single byte marker at the start of each string), or even nested structures similar to s-expressions would have avoided this.
Array of arguments is vastly superior and more secure than every program/runtime inventing a slightly different way of splitting a command string into an array of arguments. No debate. A real problem is the related birth defect in ssh2.
Well, the only other way I can think of that it could be done is the Windows way, whereby you pass the unparsed command line, spaces and all, as a string to the new process. And while this is arguably the cleaner interface, in practice it has meant even worse quote handling, since how -- or even whether -- double quotes are parsed now depends on the probably undocumented process startup code chosen by the program's compiler vendor.
Want to quote a command line that may already contain double quotes, in order to pass it as an argument to some other program? No, you don't. It isn't right to want that.
The other other way would be more structured. Arguments are not just an array, they also contain `--switch` and key/value pairs (e.g. `--key value` or `--key=value` depending on who you ask). One problem with the flat array approach is there's no way to distinguish a literal value starting with `-` from a switch, which means there needs to be some way to workaround that (and users have to remember the workaround; how often do people remember to use `rm -- "$FILENAME"`).
In practice almost every application does still need to do its own parameter parsing; a flat array is not enough.
> hope some typescript-like "typed shell" becomes mainstream someday
The trouble with trying to invent a new, more robust shell language is you basically just end up re-inventing any number of scripting languages (eg Perl, Python, awk, ...), so you might as well use one of those.
Most regular programming languages aren’t well suited for shells because they have a verbose syntax due to their readability goals. But with a shell, the vast majority of times you’re typing in stuff that you have no intention of reading back ever again.
I’ve done a fair amount of research here and I actually think we do need a new programming language for the shell (and then I created one).
Excellent article, thanks for the link. I do agree with the premise. But every time I write some Bash code and think there should be a better way to do this, I ask myself why I don't just learn Perl. I dunno. Feels like inventing another solution would just hit the old "there are now 14 standards" problem where it would solve some problems but introduce others (see: PowerShell).
That's a literal ~ in your path, the exact problem the blog post talks about.
Your use doesn't count as a "word", per man
bash. Tilde is only expanded to home at the start of a typically whitespace-separated word, and your tilde is in the middle of one.
> If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (…) are considered a tilde-prefix. (…)
> word A sequence of characters considered as a single unit by the shell. Also known as a token.
My initial syntax does work in dash (and bash), but all these shells appear to rely on expanding ~ inside a word, that your source asserts is not POSIX (which I do not contest).
Perhaps a succinct and compliant expression could be:
export PATH="$PATH:$(printf %s ~/.local/bin)"
That comes at the cost of forking a subsell.
Edit: 2.6.1 Tilde Expansion in the POSIX standard says that ~ may be expanded "following any unquoted <colon>".
Good decision and avoid the shell
whenever you can. Too late for me. I did my fair share of shell programming (and learned if from some real masters) so that my mind is already encumbered. My confidence in being able to write a longer or more complex shell script with 0 errors is still 0, so it gives me nothing.
While we're all getting pedantic and esoteric, in zsh you can do this:
path+=(~/.local/bin)
You don't even have to use the "export" keyword. Not that I would do this, but since we're all pointing out random shell stuff...
(In zsh the lowercase "path" variable is an array that's automatically tied to the $PATH string, so you can just add to it using parens to signify new array elements, separated by a space.)
Not necessarily about tildes but about some of the craziness that can happen with bash at large orgs:
At a past job, I was trying to figure out what part of my basrhc was setting a particular environment variable. I assumed that it must be some kind of default installed in my user profile and/or inheriting from /etc/<something>.
I realized pretty quickly that my bashrc was importing some other files. Again, the assumption was that this would be one file deep in the import.
It turned out there were 10+ layers of import starting from an "ur-bashrc" and then layer upon layer of more and more imports to finally get to a user level profile.
I was going to say “it always seems to work for me” then I saw “… actually works in Bash and Zsh, because …”.
Another Bash-ism I need to be careful not to use when trying to be portable.
It is worth noting that on a lot of systems /bin/sh isn't bash (or zsh) so if you want to rely on Bashisms (or just can't be bothered looking for them) be specific and use “#!/bin/bash” for you hashbang. On Debian and similar it is usually dash for instance.
For various embedded environments that use busybox it's busybox's brand of ash. I generally enjoy the opportunity to learn when bumping up against these kind of edge cases.
I wish Linux distros would ship a "Terminal"/"CLI" program etc that is decoupled from the scripting language. Have a universal Path env var that isn't tied to a specific shell. Lets you execute cd commands, launch python/git/cargo/arbitrary applications etc, and have a good bookmark + autocomplete system. It feels like the conflation of scripting language + CLI application is the root of these complications and subtleties.
If you are using shell scripting (And prefer Bash etc over Python), you would keep using Bash/Fish/Zsh etc. If you are using the CLI to launch applications that don't have a GUI, navigate directories and perform file system operations, then you would use the plain terminal.
It is - this is why adding something to the Path is tricky on Linux. Or I should say, there is a mismatch between the common instruction of how to do it (export) vs what you have to do (e.g. edit bash config)
That’s because there isn’t a universal PATH variable.
Env vars are not global. They just have that illusion because a fork() by default will pass your running env vars to the child. Thus trickling that value down.
How are you installing it? Normally package managers will symlink it into a system defined $PATH directory so you shouldn’t need to faff with $PATH yourself.
Not all applications executable match the application name (eg Visual Studio Code is just “code”). So could that have been the issue?
Depends on the software. Generally, whatever the official installation instructions are.
> So could that have been the issue?
No. Adding things to the path is a reasonably common operation on all OSes and CLI-based software. Sometimes the installer will handle it for you; sometimes it won't. (This may be out of date, but I believe the Rust install script is an example of one that sets it up; Go is one that doesn't, and its official instructions CAO 6 months ago were to use Export, which doesn't work once you reboot)
It is a clear example of RTFM!
An expansion is no a variable. An expansion not expands under quotes.
A variable expansion is not simply an expansion as it is between brackets.
Again RTFM instead of wait for a miracle of your agent.
Ehh, there are many, many (documented) gotchas about commonly used software that routinely bite people. Yes, it would be great if everyone were an expert in how every aspect of their toolkit works, but that is not practical.
Just maybe, just maybe reserving somethings is not a bad idea... Whatever the fanatics say... There is enough features in shell that maybe banning somethings would be correct design.
I was expecting this article to be about skew between HOME environment variable and getpwent(3) (usually from /etc/passed) views of the home directory.
They can be different things. Suppose your user is foobar, ordinarily homed at /home/foobar. You can write HOME=/tmp/my-test-home. Then, ~/qux will become/tmp/my-test-home instead of the usual /home/foobar/qux. That's because bash and zsh use HOME to resolve ~.
Almost. If you write ~foobar/qux, you get /home/foobar/qux again because the ~-with-username syntax looks up the getpwent home directory not the environment one.
And of course language runtimes are all schizo about whether the "user home directory" API uses HOME or the getpwent database or whatever to determine the home directory.
It's a mess, TBH. It used to be useful to temporarily bind HOME to something else to do things like create isolated test environments. Now, because of the aforementioned schizo sprinkler of randomness in the environment, you're going to have a bad time if you don't keep HOME synced to getpwent home directory.
Afaik it's habit to give system paths precedence so a malicious script can't shadow e.g. sudo and steal your password, escalating a local file write into root
In most use cases, the bash scripts location is more important than $HOME. This is because it is resilient to changes in user in the session, and parent process current working location contexts. =3
In fish, you can just do `fish_add_path ~/.local/bin`. Adding a directory to your PATH is so common that there’s a function to do it. And it takes effect immediately in all running instances of the shell.
So many headaches could be avoided if we only allowed `[A-Za-z0-9._-]` in paths. (Arguably, even `-` can be problematic.) Encoding issues, expansion, parameter separation, ... and I never saw a convincing case in favor of supporting anything else.
The language I grew up with does use non latin letters, I can manage. Then again, it's only four of them, so I get your point ... but I can dream, can't I?
Any fule no that a file name is just an array of bytes (excluding the null byte and the slash). You can create a file with a name that is an invalid UTF-8 encoding. It's fun to see how much software chokes on that!
I always joked about setting a custom keyboard layout to replace the space char with the underscore char specifically for avoiding spaces in file paths.
This is almost never what you actually want, and in the rare cases that you do want to store a list, the shell's implicit space splitting usually breaks on filenames containing spaces. Bash has actual array variables which make it possible, but horrible, to handle this in a first-class way:
This feature is absent in the Bourne shell and in dash.In general, whenever you see a $variable $expansion in a shell script outside of double quotes, you should suspect that the shell script will probably fail if your filenames or directory names contain spaces. In very many cases, this results in path injection security vulnerabilities. There are contexts where unquoted $variable $expansion is safe, but they are relatively rare.
Have I run into this at some point?
I certainly have.
Have I learned to quote better and only where appropriate from it?
I certainly have.
Bourne compatible shells take a while to learn and require some experience. This won't change, but alternatives exist, with their own caveats.
[1]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V...
[Insert mild rant on kids these days having no attention span any more]
I've also seen this even with people who seem like generally competent shell users. Idrgi
I don't use WYSIWYG editors anymore, so I have to remind myself to use those when writing raw HTML text. Although, most browsers correct raw ' and " symbols in text now, I still try to use them to have compliant HTML
Using ' and " to pretend to be ‘/’ or “/” is on par with the typewriter days where people would use the l key to stand in for 1 also. A justifiable approximation when technology limitations prevented using the real deal, but an approximation all the same.
The equivalent of l for 1 is doing font-specific pseudo smart quotes with ` and '
" can be inches or arcseconds from cartography.
' can be feet (of measure) or arcminutes from cartography.
These actually all have slightly different symbols, and the symbols for the left/right quotation marks are actually farthest from this approximation, even if they are the most frequent usage.
It’s always been wrong in some respect to use a single available symbol to emulate three or more different typographical tasks, but quotation marks may actually be the one where the emulation is the most wrong.
GENERAL RULE
1. Double-quote dollar sign expressions, and nothing else.
2. Single-quote words with a literal special character, and nothing else. ---I should point out that the author's example is NOT fixed by different quoting though.
Because tilde expansion only happens at the beginning of the word.Sure, but I would say you almost always want to add to the start of the PATH, not to the end.
* https://man.freebsd.org/cgi/man.cgi?query=login.conf&sektion...
So putting the addition of things like ~/bin to PATH in /etc/login_conf and ~/.login_conf instead of shell scripts is another way to address it.
It's particularly handy when there are multiple login shells in use.* http://jdebp.uk./FGA/BSDs-for-Linux-users/login-conf.html
Powershell is, as I understand it, not available on Linux but is omnipresent on Windows, so hopefully the windows folks can use it like they would bash.
Because Windows is tied together through APIs and databases and not text files (unlike Linux), everything is text is not as useful as something that can talk objects. And a lot of Windows is object oriented, from the window message dispatching system through COM and down to NT's object manager.
Such as Fish, nushell, Elvish, or the project I help maintain, “murex”
Ruby replaced all my shell needs. Almost 25 years ago. I even have a shell written in ruby (it handles both bash-like behaviour as well as ruby code as-is); admittedly it is not quite perfect for everything, but I improve on it steadily. And it works on Windows too, which was one reason I wrote it in the first place (need to have it work via cmd.exe as-is).
Never looked back to shell. It is too awful to use.
Windows, on the other hand, only passes one string. So it’s up to the application to choose how to handle whitespace, quotation marks, and other nuances with parsing parameters.
Variable expansion in Bash is lazy. But there’s no reason why variables cannot be tokenised so that strings with spaces aren’t treated as multiple parameters. And in fact that’s exactly how some other shells work, such as the one I maintain.
A typed array (e.g. by having a required single byte marker at the start of each string), or even nested structures similar to s-expressions would have avoided this.
Want to quote a command line that may already contain double quotes, in order to pass it as an argument to some other program? No, you don't. It isn't right to want that.
In practice almost every application does still need to do its own parameter parsing; a flat array is not enough.
sometimes, its footguns seem worse than javascript...
hope some typescript-like "typed shell" becomes mainstream someday
The trouble with trying to invent a new, more robust shell language is you basically just end up re-inventing any number of scripting languages (eg Perl, Python, awk, ...), so you might as well use one of those.
I’ve done a fair amount of research here and I actually think we do need a new programming language for the shell (and then I created one).
I wrote a blog about this problem: https://murex.rocks/blog/split_personalities.html#conclusion
Might want to check out nushell (https://www.nushell.sh/)
The enlightened answer "You should use A, B or C for these reasons"
Even though bash is installed on many systems, I try to encourage people to use better designed shells that have less of these footguns :
Fish (https://fishshell.com/): No implicit word splitting : spaces in variables won't unexpectedly become separate arguments.
Zsh (I use this: https://ohmyz.sh/): Arrays start at 1 by default, but crucially, unquoted variables don't implicitly split into multiple arguments.
Nushell (https://www.nushell.sh/): Passes structured tables and records between commands : avoids fragile parsing of text with awk/grep.
Edit: this appears to work properly with mksh on my phone:
Your use doesn't count as a "word", per man bash. Tilde is only expanded to home at the start of a typically whitespace-separated word, and your tilde is in the middle of one.
> If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (…) are considered a tilde-prefix. (…)
> word A sequence of characters considered as a single unit by the shell. Also known as a token.
Perhaps a succinct and compliant expression could be:
That comes at the cost of forking a subsell.Edit: 2.6.1 Tilde Expansion in the POSIX standard says that ~ may be expanded "following any unquoted <colon>".
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V...
That being so, the most succinct and compliant version is my first variant, with the colon moved outside the quotes:
Thank you for prompting me to look this up.$HOME otherwise, which still has gotchas but they are the same as any other environment variable.
The more specific you are, the less gotchas you're going to fall to.
If your concern is that some hacker could put an illicit binary in ~/.local/bin, then your security problems are much deeper than your PATH order.
path+=(~/.local/bin)
You don't even have to use the "export" keyword. Not that I would do this, but since we're all pointing out random shell stuff...
(In zsh the lowercase "path" variable is an array that's automatically tied to the $PATH string, so you can just add to it using parens to signify new array elements, separated by a space.)
At a past job, I was trying to figure out what part of my basrhc was setting a particular environment variable. I assumed that it must be some kind of default installed in my user profile and/or inheriting from /etc/<something>.
I realized pretty quickly that my bashrc was importing some other files. Again, the assumption was that this would be one file deep in the import.
It turned out there were 10+ layers of import starting from an "ur-bashrc" and then layer upon layer of more and more imports to finally get to a user level profile.
It was so convoluted that I was going nuts until I found this Stack Exchange post: https://unix.stackexchange.com/questions/813/how-to-determin...
It turns on "tracing" for bash imports so that you can then narrow down on where the env variable is getting set.
Another Bash-ism I need to be careful not to use when trying to be portable.
It is worth noting that on a lot of systems /bin/sh isn't bash (or zsh) so if you want to rely on Bashisms (or just can't be bothered looking for them) be specific and use “#!/bin/bash” for you hashbang. On Debian and similar it is usually dash for instance.
If you are using shell scripting (And prefer Bash etc over Python), you would keep using Bash/Fish/Zsh etc. If you are using the CLI to launch applications that don't have a GUI, navigate directories and perform file system operations, then you would use the plain terminal.
This sounds like Windows. ;)
Environment variables are stored in the registry; for the user, it's
and for system-wide env vars, it'sEnv vars are not global. They just have that illusion because a fork() by default will pass your running env vars to the child. Thus trickling that value down.
Not all applications executable match the application name (eg Visual Studio Code is just “code”). So could that have been the issue?
> So could that have been the issue?
No. Adding things to the path is a reasonably common operation on all OSes and CLI-based software. Sometimes the installer will handle it for you; sometimes it won't. (This may be out of date, but I believe the Rust install script is an example of one that sets it up; Go is one that doesn't, and its official instructions CAO 6 months ago were to use Export, which doesn't work once you reboot)
I'm not sure why this can't be done. Security people will have a million reasons, I guess it's possible one of them might be valid.
It sounds like you could make it yourself in ~10 lines of Python or bash. I don't see it catching on, though.
Big brain time here
Again RTFM instead of wait for a miracle of your agent.
That was a scary mistake to unwind!
Hilarious!
They can be different things. Suppose your user is foobar, ordinarily homed at /home/foobar. You can write HOME=/tmp/my-test-home. Then, ~/qux will become/tmp/my-test-home instead of the usual /home/foobar/qux. That's because bash and zsh use HOME to resolve ~.
Almost. If you write ~foobar/qux, you get /home/foobar/qux again because the ~-with-username syntax looks up the getpwent home directory not the environment one.
And of course language runtimes are all schizo about whether the "user home directory" API uses HOME or the getpwent database or whatever to determine the home directory.
It's a mess, TBH. It used to be useful to temporarily bind HOME to something else to do things like create isolated test environments. Now, because of the aforementioned schizo sprinkler of randomness in the environment, you're going to have a bad time if you don't keep HOME synced to getpwent home directory.
Also, if something can write into your path, it can probably write to your shell config and/or the environment variables.
It is a theoretically nice ideal that fails immediately when you want project specific overrides.
I've always seen home dir, homebrew, etc prepending to PATH.
Most people know better.
Tilde expands when at the beginning of an unquoted word.
Pretty straightforward.
---Bash has a few extra.
scriptPath=$(/usr/bin/realpath "${BASH_SOURCE[0]}")
localPath=$(/usr/bin/dirname "$scriptPath" )
/usr/bin/echo "localPath = '$localPath'"
https://fishshell.com/docs/current/cmds/fish_add_path.html
The (classical) Latin alphabet can be fully described by the English alphabet.
And allowing any letters from any language is probably worth the hassle.