28 comments

  • amarshall8 hours ago
    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"`).
    • kragen1 hour ago
      Not quoting the tilde doesn&#x27;t help:<p><pre><code> : tmp; echo $PATH:~ &#x2F;usr&#x2F;local&#x2F;bin:&#x2F;usr&#x2F;bin:&#x2F;bin:&#x2F;usr&#x2F;local&#x2F;games:&#x2F;usr&#x2F;games:~ </code></pre> Edit: mjmas points out that I am wrong, because different Calvinball rules apply to variable assignments:<p><pre><code> : tmp; x=$PATH:~ : tmp; echo &quot;$x&quot; &#x2F;usr&#x2F;local&#x2F;bin:&#x2F;usr&#x2F;bin:&#x2F;bin:&#x2F;usr&#x2F;local&#x2F;games:&#x2F;usr&#x2F;games:&#x2F;home&#x2F;user </code></pre> 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&#x27;re storing in the variable is not an atomic string but rather a space-separated list.<p>This is almost never what you actually want, and in the rare cases that you <i>do</i> want to store a list, the shell&#x27;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:<p><pre><code> : tmp; x=(&quot;foo bar&quot; baz) : tmp; echo &quot;${x[@]}&quot; foo bar baz : tmp; touch &quot;${x[@]}&quot; : tmp; ls -l &quot;${x[@]}&quot; -rw-r--r-- 1 user user 0 Oct 11 17:52 baz -rw-r--r-- 1 user user 0 Oct 11 17:52 &#x27;foo bar&#x27; </code></pre> This ksh feature is absent in the Bourne shell and in dash, but MirBSD ksh, Bash, and zsh all have it.<p>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.<p>However, relevant detail here! One of those safe contexts is actually variable assignment, where as mjmas pointed out in their helpful comment below, unquoted variable expansion is actually perfectly safe:<p><pre><code> : tmp; a=&#x27;x y&#x27; : tmp; b=α:$a:ω : tmp; echo &quot;$b&quot; α:x y:ω</code></pre>
      • mjmas1 hour ago
        Bash does it only inside variable assignments:<p><pre><code> a=123:~ echo $a echo 123:~ </code></pre> results in:<p><pre><code> 123:&#x2F;home&#x2F;me 123:~</code></pre>
        • kragen52 minutes ago
          Oh, thank you for the correction. I was wrong about that. Calvinball.
    • Cockbrand7 hours ago
      I feel like this is common knowledge and should not be worth mentioning. But then it apparently is not common knowledge, as the article proves.<p>Have I run into this at some point?<p>I certainly have.<p>Have I learned to quote better and only where appropriate from it?<p>I certainly have.<p>Bourne compatible shells take a while to learn and require some experience. This won&#x27;t change, but alternatives exist, with their own caveats.
      • MathMonkeyMan2 hours ago
        Almost nobody that I&#x27;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.<p>[1]: <a href="https:&#x2F;&#x2F;pubs.opengroup.org&#x2F;onlinepubs&#x2F;9799919799&#x2F;utilities&#x2F;V3_chap02.html" rel="nofollow">https:&#x2F;&#x2F;pubs.opengroup.org&#x2F;onlinepubs&#x2F;9799919799&#x2F;utilities&#x2F;V...</a>
        • Cockbrand1 hour ago
          I learned this stuff from friends, O&#x27;Reilly books and endless nights of failure and trial and error. I&#x27;m certainly not a super wizard, but I feel like I&#x27;m not missing any shell skills to be able to do what I need to do.<p>[Insert mild rant on kids these days having no attention span any more]
        • jolux1 hour ago
          also poorly organized and formatted.
    • isityettime2 hours ago
      This feature, or at least the syntactic unit in question has a name here &quot;bare words&quot;. You also have these in some contexts in Perl and Ruby, YAML, and probably some other languages, idk.<p>I&#x27;ve also seen this even with people who seem like generally competent shell users. Idrgi
    • dylan6048 hours ago
      Unless you&#x27;re running a shell command from python. That was the first time I saw a command string broken down into &quot;string&quot; arguments for every thing like that.
      • thwarted8 hours ago
        In that case, you&#x27;re not running a &quot;shell command&quot; from python, you&#x27;re passing arguments to exec. A shell command would be a string interpreted by the shell, and you&#x27;d use that for shell syntax things like having the shell do variable interpolation or redirections as part of executing the command.
    • cr125rider8 hours ago
      The trick is to quote explicitly and correctly. “ and ‘ are different.
      • dylan6048 hours ago
        why would you use smart quotes in a terminal like that?
        • tom_8 hours ago
          They probably fell foul of some browser text box auto-correct.
          • dylan6046 hours ago
            &amp;apos; &amp;quot;<p>I don&#x27;t use WYSIWYG editors anymore, so I have to remind myself to use those when writing raw HTML text. Although, most browsers correct raw &#x27; and &quot; symbols in text now, I still try to use them to have compliant HTML
        • airstrike8 hours ago
          why would anyone use smart quotes ever
          • mpyne7 hours ago
            They are typographically the right thing to have been using all along.<p>Using &#x27; and &quot; to pretend to be ‘&#x2F;’ or “&#x2F;” 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.
            • dmd6 hours ago
              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.
              • kragen1 hour ago
                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&#x27;s mostly forgotten.
            • airstrike3 hours ago
              Can&#x27;t that be handled by the typesetting&#x2F;rendering software and displayed appropriately regardless of which specific character was typed?
              • kragen56 minutes ago
                No, because it&#x27;s missing semantic information carried by the distinction. The ’ at the beginning of<p><pre><code> ’Tis brillig, and the slithy toves </code></pre> is not a left quote ‘ but an apostrophe ’, like the apostrophe in “can’t”; but ‘tis certainly possible that someone might want to put single quotes around a phrase beginning with the word “tis”, such as the Latin ‘tis misereri’. By contrast to “can’t”, the ‘ in “Hawai’i” is the ’okina used to represent the glottal-stop sound in the Hawai’ian language, not an apostrophe.
            • Dylan168077 hours ago
              Except l has a specific meaning that isn&#x27;t 1, while the entire purpose of &#x27; and &quot; is quoting (and apostrophe).<p>The equivalent of l for 1 is doing font-specific pseudo smart quotes with ` and &#x27;
              • mpyne5 hours ago
                &quot; and &#x27; are themselves conjoined with other uses.<p>&quot; can be inches or arcseconds from cartography.<p>&#x27; can be feet (of measure) or arcminutes from cartography.<p>These actually all have slightly different symbols, and the symbols for the left&#x2F;right quotation marks are actually farthest from this approximation, even if they are the most frequent usage.<p>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.
                • kragen55 minutes ago
                  Overstriking &#x27; was commonly used (on typewriters and ASCII printers) for acute accents, and overstriking &quot; was commonly used for a diaeresis. The glyphs used in typewriter fonts and traditional (pre-Unicode) Unix terminal fonts are compromises between these different uses.
                • dasyatidprime28 minutes ago
                  Aside: in Unicode we now have ″ and ′ for that. Also the triple variant: ‴
              • opello5 hours ago
                That equivalency only holds if there is a visual distinction in the output between the l and the 1. There often wasn&#x27;t when this practice was popular.
          • thaumasiotes2 hours ago
            As others have commented, for the same reason that we use smart parentheses instead of the more utilitarian |.
    • paulddraper8 hours ago
      People quote both too often and too little.<p>GENERAL RULE<p>1. Double-quote dollar sign expressions, and nothing else.<p><pre><code> foo &quot;$bar&quot;&#x2F;foo baz:&quot;$(cat example.txt)&quot; exec cmd &quot;$@&quot; </code></pre> 2. Single-quote words with a literal special character, and nothing else.<p><pre><code> &#x27;Die Hard&#x27; &#x27;ke$ha&#x27; </code></pre> ---<p>I should point out that the author&#x27;s example is NOT fixed by different quoting though.<p><pre><code> # original export PATH=&quot;$PATH:~&#x2F;.local&#x2F;bin&#x2F;&quot; # without unnecessary quotes export PATH=&quot;$PATH&quot;:~&#x2F;.local&#x2F;bin&#x2F; </code></pre> Because tilde expansion only happens at the beginning of the word.
      • gray_-_wolf3 hours ago
        &gt; I should point out that the author&#x27;s example is NOT fixed by different quoting though.<p>Sure, but I would say you almost always want to add to the start of the PATH, not to the end.
        • GrinningFool1 hour ago
          I used to put it first for convenience, but got increasingly paranoid about something same-named getting slipped into my ~&#x2F;.local&#x2F;bin; now it lives at the end.
      • JdeBP7 hours ago
        The Z shell&#x27;s, C shell&#x27;s, and others&#x27;s syntaxes for setting the PATH environment variable via a shell array variable alias also does the tilde expansion.<p><pre><code> path=( $path ~&#x2F;bin ) </code></pre> It&#x27;s worth noting, also, that the path and manpath settings in login.conf(5) expand leading tildes in individual search path items.<p>* <a href="https:&#x2F;&#x2F;man.freebsd.org&#x2F;cgi&#x2F;man.cgi?query=login.conf&amp;sektion=5" rel="nofollow">https:&#x2F;&#x2F;man.freebsd.org&#x2F;cgi&#x2F;man.cgi?query=login.conf&amp;sektion...</a><p>So putting the addition of things like ~&#x2F;bin to PATH in &#x2F;etc&#x2F;login_conf and ~&#x2F;.login_conf instead of shell scripts is another way to address it.<p><pre><code> :path=~&#x2F;bin &#x2F;usr&#x2F;local&#x2F;bin &#x2F;usr&#x2F;pkg&#x2F;bin &#x2F;usr&#x2F;bin &#x2F;bin: </code></pre> It&#x27;s particularly handy when there are multiple login shells in use.<p>* <a href="http:&#x2F;&#x2F;jdebp.uk.&#x2F;FGA&#x2F;BSDs-for-Linux-users&#x2F;login-conf.html" rel="nofollow">http:&#x2F;&#x2F;jdebp.uk.&#x2F;FGA&#x2F;BSDs-for-Linux-users&#x2F;login-conf.html</a>
    • vips7L8 hours ago
      Or just stop using bash. It’s a terrible language to write and has tons of footguns.
      • yjftsjthsd-h6 hours ago
        For the things shell is good at (running other commands, pipes, and shuffling files), I have yet to find anything even close to as good.
        • hnlmorg5 hours ago
          I agree that shells are uniquely good for that but there are plenty of better shells than Bash.<p>Such as Fish, nushell, Elvish, or the project I help maintain, “murex”
          • bornfreddy5 hours ago
            None that I can rely on being available wherever I see a terminal. It&#x27;s bash or sh as far as I&#x27;m concerned.
            • xigoi4 hours ago
              Fortunately, 99.9% of the time I’m on my computer, where I can install whatever I want.
              • ifwinterco3 hours ago
                Then you ssh into an instance and have to remember how bash&#x2F;sh work
                • gavmor2 hours ago
                  At what point does an alternate shell get baked into the image?
        • vips7L5 hours ago
          A different shell??? Nushell, fish, powershell, etc.
          • yjftsjthsd-h4 hours ago
            Oh, you mean bash <i>specifically</i>. Then yeah, that&#x27;s reasonable enough. Although I agree with the other commenter that sh&#x2F;bash have the advantage of ubiquity.
          • lelandbatey5 hours ago
            None of those have the #1 best thing bash is good at: bash is already installed, nushell and fish are not.<p>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.
            • yjftsjthsd-h4 hours ago
              No, powershell runs on Linux, it just sucks because it wants objects and everything on *nix speaks streams of text.
            • barrkel4 hours ago
              PowerShell works on Windows because of WMI, to a first approximation.<p>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&#x27;s object manager.
        • shevy-java4 hours ago
          I did.<p>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).<p>Never looked back to shell. It is too awful to use.
      • CodesInChaos7 hours ago
        Unfortunately half of its badness isn&#x27;t isn&#x27;t the shell itself, but the convention of how parameters are passed to processes on Unix systems.
        • hnlmorg6 hours ago
          That’s not correct because POSIX passes what is ostensibly an array of strings.<p>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.<p>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.
          • CodesInChaos1 hour ago
            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&#x27;s inconsistently implemented and the caller has to actively remember to use it.<p>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.
        • formerly_proven7 hours ago
          Array of arguments is vastly superior and more secure than every program&#x2F;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.
        • akoboldfrying7 hours ago
          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 <i>even worse</i> quote handling, since how -- or even whether -- double quotes are parsed now depends on the <i>probably undocumented process startup code chosen by the program&#x27;s compiler vendor</i>.<p>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&#x27;t. It <i>isn&#x27;t right</i> to want that.
          • ChrisSD5 hours ago
            The other other way would be more structured. Arguments are not just an array, they also contain `--switch` and key&#x2F;value pairs (e.g. `--key value` or `--key=value` depending on who you ask). One problem with the flat array approach is there&#x27;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 -- &quot;$FILENAME&quot;`).<p>In practice almost every application does still need to do its own parameter parsing; a flat array is not enough.
        • sysguest6 hours ago
          yeah but... that convention is so much of a security&#x2F;bug headache<p>sometimes, its footguns seem worse than javascript...<p>hope some typescript-like &quot;typed shell&quot; becomes mainstream someday
          • coldpie6 hours ago
            &gt; hope some typescript-like &quot;typed shell&quot; becomes mainstream someday<p>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.
            • hnlmorg5 hours ago
              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.<p>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).<p>I wrote a blog about this problem: <a href="https:&#x2F;&#x2F;murex.rocks&#x2F;blog&#x2F;split_personalities.html#conclusion" rel="nofollow">https:&#x2F;&#x2F;murex.rocks&#x2F;blog&#x2F;split_personalities.html#conclusion</a>
              • coldpie5 hours ago
                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&#x27;t just learn Perl. I dunno. Feels like inventing another solution would just hit the old &quot;there are now 14 standards&quot; problem where it would solve some problems but introduce others (see: PowerShell).
                • hnlmorg4 hours ago
                  I don’t disagree with you per se. But if the new shell solves enough annoying problems then I think it has merit in existing.
          • ravenical4 hours ago
            &gt; hope some typescript-like &quot;typed shell&quot; becomes mainstream someday<p>Might want to check out nushell (<a href="https:&#x2F;&#x2F;www.nushell.sh&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.nushell.sh&#x2F;</a>)
          • colejohnson663 hours ago
            PowerShell
      • malux856 hours ago
        The widwit answer: &quot;Dont do X&quot; (and nothing more)<p>The enlightened answer &quot;You should use A, B or C for these reasons&quot;<p>Even though bash is installed on many systems, I try to encourage people to use better designed shells that have less of these footguns :<p>Fish (<a href="https:&#x2F;&#x2F;fishshell.com&#x2F;" rel="nofollow">https:&#x2F;&#x2F;fishshell.com&#x2F;</a>): No implicit word splitting : spaces in variables won&#x27;t unexpectedly become separate arguments.<p>Zsh (I use this: <a href="https:&#x2F;&#x2F;ohmyz.sh&#x2F;" rel="nofollow">https:&#x2F;&#x2F;ohmyz.sh&#x2F;</a>): Arrays start at 1 by default, but crucially, unquoted variables don&#x27;t implicitly split into multiple arguments.<p>Nushell (<a href="https:&#x2F;&#x2F;www.nushell.sh&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.nushell.sh&#x2F;</a>): Passes structured tables and records between commands : avoids fragile parsing of text with awk&#x2F;grep.
    • Grimeton3 hours ago
      You need to read the manual.
    • chasil6 hours ago
      I think the appropriate method by POSIX rules would be:<p><pre><code> export PATH=&quot;$PATH:&quot;~&#x2F;.local&#x2F;bin </code></pre> I may be wrong. If I&#x27;m not, that works in any POSIX-compliant shell.<p>Edit: this appears to work properly with mksh on my phone:<p><pre><code> :&#x2F; $ export PATH=&quot;$PATH:&quot;~&#x2F;.local&#x2F;bin :&#x2F; $ print $PATH &#x2F;product&#x2F;bin:&#x2F;apex&#x2F;com.android.runtime&#x2F;bin:&#x2F;apex&#x2F;com.android.art&#x2F;bin:&#x2F;system_ext&#x2F;bin:&#x2F;system&#x2F;bin:&#x2F;system&#x2F;xbin:&#x2F;odm&#x2F;bin:&#x2F;vendor&#x2F;bin:&#x2F;vendor&#x2F;xbin:~&#x2F;.local&#x2F;bin</code></pre>
      • yencabulator5 hours ago
        That&#x27;s a literal ~ in your path, the exact problem the blog post talks about.<p>Your use doesn&#x27;t count as a &quot;word&quot;, 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.<p>&gt; If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (…) are considered a tilde-prefix. (…)<p>&gt; word A sequence of characters considered as a single unit by the shell. Also known as a token.
        • chasil4 hours ago
          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).<p>Perhaps a succinct and compliant expression could be:<p><pre><code> export PATH=&quot;$PATH:$(printf %s ~&#x2F;.local&#x2F;bin)&quot; </code></pre> That comes at the cost of forking a subsell.<p>Edit: <i>2.6.1 Tilde Expansion</i> in the POSIX standard says that ~ may be expanded &quot;following any unquoted &lt;colon&gt;&quot;.<p><a href="https:&#x2F;&#x2F;pubs.opengroup.org&#x2F;onlinepubs&#x2F;9699919799&#x2F;utilities&#x2F;V3_chap02.html#tag_18_06_01" rel="nofollow">https:&#x2F;&#x2F;pubs.opengroup.org&#x2F;onlinepubs&#x2F;9699919799&#x2F;utilities&#x2F;V...</a><p>That being so, the most succinct and compliant version is my first variant, with the colon moved outside the quotes:<p><pre><code> export PATH=&quot;$PATH&quot;:~&#x2F;.local&#x2F;bin </code></pre> Thank you for prompting me to look this up.
  • SoftTalker6 hours ago
    I never use tilde in scripts, only as a convenience when typing commands interactively.<p>$HOME otherwise, which still has gotchas but they are the same as any other environment variable.
    • ndegruchy5 hours ago
      Yeah, in scripts I try to be as explicit as possible. `$HOME` for the home directory, `$XDG_DATA_HOME` for `&#x2F;home&#x2F;foo&#x2F;.local&#x2F;share&#x2F;`, etc.<p>The more specific you are, the less gotchas you&#x27;re going to fall to.
  • nlehuen2 hours ago
    I refuse to let knowledge about Calvinball-level grotesque rules about quoting and escaping in bash encumber my mind.
    • weinzierl2 hours ago
      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.
  • FeepingCreature8 hours ago
    Kind of seems like you should have noticed this by your ~&#x2F;.local&#x2F;bin PATH not working?
  • ultraboom32 minutes ago
    The bash man page is comprehensive, precise, and well-written. A recommended read for any bash user.
  • thefilmore4 hours ago
    You can just do:<p><pre><code> PATH=~&#x2F;.local&#x2F;bin:$PATH </code></pre> PATH is already exported. Quotes are also not necessary for assignments.
    • stkdump3 hours ago
      Looks dangerous to put a user writable directory ahead of system directories in PATH
      • bityard2 hours ago
        Nah, it&#x27;s totally normal because you often want to deliberately override or wrap system commands for various good and convenient reasons.<p>If your concern is that some hacker could put an illicit binary in ~&#x2F;.local&#x2F;bin, then your security problems are much deeper than your PATH order.
    • russellbeattie3 hours ago
      While we&#x27;re all getting pedantic and esoteric, in zsh you can do this:<p>path+=(~&#x2F;.local&#x2F;bin)<p>You don&#x27;t even have to use the &quot;export&quot; keyword. Not that I would do this, but since we&#x27;re all pointing out random shell stuff...<p><i>(In zsh the lowercase &quot;path&quot; variable is an array that&#x27;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.)</i>
  • alexpotato7 hours ago
    Not necessarily about tildes but about some of the craziness that can happen with bash at large orgs:<p>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&#x2F;or inheriting from &#x2F;etc&#x2F;&lt;something&gt;.<p>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.<p>It turned out there were 10+ layers of import starting from an &quot;ur-bashrc&quot; and then layer upon layer of more and more imports to finally get to a user level profile.<p>It was so convoluted that I was going nuts until I found this Stack Exchange post: <a href="https:&#x2F;&#x2F;unix.stackexchange.com&#x2F;questions&#x2F;813&#x2F;how-to-determine-where-an-environment-variable-came-from&#x2F;154971#154971" rel="nofollow">https:&#x2F;&#x2F;unix.stackexchange.com&#x2F;questions&#x2F;813&#x2F;how-to-determin...</a><p>It turns on &quot;tracing&quot; for bash imports so that you can then narrow down on where the env variable is getting set.
  • dspillett7 hours ago
    I was going to say “it always seems to work for me” then I saw “… actually works in Bash and Zsh, because …”.<p>Another Bash-ism I need to be careful not to use when trying to be portable.<p>It is worth noting that on a lot of systems &#x2F;bin&#x2F;sh <i>isn&#x27;t</i> bash (or zsh) so if you want to rely on Bashisms (or just can&#x27;t be bothered looking for them) be specific and use “#!&#x2F;bin&#x2F;bash” for you hashbang. On Debian and similar it is usually dash for instance.
    • opello5 hours ago
      For various embedded environments that use busybox it&#x27;s busybox&#x27;s brand of ash. I generally enjoy the opportunity to learn when bumping up against these kind of edge cases.
  • the__alchemist7 hours ago
    I wish Linux distros would ship a &quot;Terminal&quot;&#x2F;&quot;CLI&quot; program etc that is decoupled from the scripting language. Have a universal <i>Path</i> env var that isn&#x27;t tied to a specific shell. Lets you execute cd commands, launch python&#x2F;git&#x2F;cargo&#x2F;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.<p>If you are using shell scripting (And prefer Bash etc over Python), you would keep using Bash&#x2F;Fish&#x2F;Zsh etc. If you are using the CLI to launch applications that don&#x27;t have a GUI, navigate directories and perform file system operations, then you would use the plain terminal.
    • delta_p_delta_x1 hour ago
      &gt; Have a universal Path env var that isn&#x27;t tied to a specific shell<p>This sounds like Windows. ;)<p>Environment variables are stored in the registry; for the user, it&#x27;s<p><pre><code> HKCU\Environment </code></pre> and for system-wide env vars, it&#x27;s<p><pre><code> HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment</code></pre>
    • dicytea7 hours ago
      $PATH is not tied to any specific shell. And what you&#x27;re describing <i>is</i> a <i>shell</i>, so I&#x27;m not sure how it&#x27;s any different from existing solutions.
      • the__alchemist7 hours ago
        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)
        • hnlmorg5 hours ago
          That’s because there isn’t a universal PATH variable.<p>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.
          • the__alchemist5 hours ago
            Exactly. It&#x27;s annoying if I&#x27;m just trying to launch an application I installed by typing its name, which is IMO what PATH is for.
            • hnlmorg4 hours ago
              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.<p>Not all applications executable match the application name (eg Visual Studio Code is just “code”). So could that have been the issue?
              • the__alchemist4 hours ago
                Depends on the software. Generally, whatever the official installation instructions are.<p>&gt; So could that have been the issue?<p>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&#x27;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&#x27;t, and its official instructions CAO 6 months ago were to use Export, which doesn&#x27;t work once you reboot)
            • arccy3 hours ago
              this is why you don&#x27;t curl | bash
    • Lerc7 hours ago
      I always thought that there should be a proc style file system for simlinks to user specific data.<p>I&#x27;m not sure why this can&#x27;t be done. Security people will have a million reasons, I guess it&#x27;s possible one of them might be valid.
    • akoboldfrying7 hours ago
      IIUC, you&#x27;re describing an extremely restricted (some would say underpowered) shell.<p>It sounds like you could make it yourself in ~10 lines of Python or bash. I don&#x27;t see it catching on, though.
  • em-bee49 minutes ago
    in the days of yore, when i still was a green linux&#x2F;unix newbie i attempted to use the mirror tool (written in perl i believe) to create a mirror of something on my account. i configured the tool to write the files into a directory in my home. in the config i wrote <i>~&#x2F;somewhere</i> ...<p>after running the tool, i discovered a literal directory named &quot;~&quot;.<p>that&#x27;s wrong i thought, fixed the config and proceded to remove the offending directory:<p>rm -r ~<p>then i waited ...<p>and waited ...<p>and i started wondering why removing an almost empty directory is so slow ...<p>...<p>...<p>oh sh!!!!!!<p>...
    • em-bee41 minutes ago
      i have no recollection of what i lost that day, but i learned a few lessons:<p>prefix ambiguous paths with .&#x2F;<p><i>rm -r .&#x2F;~</i> would have worked.<p>don&#x27;t use rm -r when you can avoid it.<p><i>rmdir -p ~&#x2F;something</i> would have failed without causing damage.<p><i>rmdir -p .&#x2F;~&#x2F;something</i> would have been the best option.<p>if there are files but no subdirs inside then<p><pre><code> cd dir rm .&#x2F;* (if there is a more specific wildcard that catches all files then use that) cd .. rmdir dir </code></pre> is my preference now.
  • ligarota6 hours ago
    Juste create a file ~ which is a symlink to home :)<p>Big brain time here
    • mnw21cam2 hours ago
      In every single directory you&#x27;re ever going to have as cwd when running that software?
  • mrsssnake1 hour ago
    Is there some tool, language or way to early script together inputs and outputs or external programs, with some safety or &quot;proper&quot; (for lack of better word) programming languages but with convenience of Bash (no wrapping like &quot;exec(programname)&quot;?
    • lexicality49 minutes ago
      Perl has been the sysadmin&#x27;s friend (and enemy) for decades. You can run stuff with backticks and manipulate the results in relative safety.
  • panzi5 hours ago
    I expected it to also talk about ~username. See e.g.: echo ~root ~pulse ~sddm
  • arkt85 hours ago
    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.<p>Again RTFM instead of wait for a miracle of your agent.
    • 3eb7988a16634 hours ago
      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.
  • very_good_man8 hours ago
    Reminds me of early days of Cursor when it decided it would be a good idea to create a directory named &quot;~&quot; in my repo root!<p>That was a scary mistake to unwind!
    • Ekaros5 hours ago
      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.
  • Grimeton3 hours ago
    People only reading the manual after they shot themselves in the foot.<p>Hilarious!
  • quotemstr6 hours ago
    I was expecting this article to be about skew between HOME environment variable and getpwent(3) (usually from &#x2F;etc&#x2F;passed) views of the home directory.<p>They can be different things. Suppose your user is foobar, ordinarily homed at &#x2F;home&#x2F;foobar. You can write HOME=&#x2F;tmp&#x2F;my-test-home. Then, ~&#x2F;qux will become&#x2F;tmp&#x2F;my-test-home instead of the usual &#x2F;home&#x2F;foobar&#x2F;qux. That&#x27;s because bash and zsh use HOME to resolve ~.<p>Almost. If you write ~foobar&#x2F;qux, you get &#x2F;home&#x2F;foobar&#x2F;qux again because the ~-with-username syntax looks up the getpwent home directory not the environment one.<p>And of course language runtimes are all schizo about whether the &quot;user home directory&quot; API uses HOME or the getpwent database or whatever to determine the home directory.<p>It&#x27;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&#x27;re going to have a bad time if you don&#x27;t keep HOME synced to getpwent home directory.
  • duncangh8 hours ago
    I should have read the docs before getting ~&#x2F; tattooed on my wrist.
    • lysium6 hours ago
      If you haven’t quoted it, I think you’re fine.
      • duncangh3 hours ago
        sometimes I feel like my environment isn’t properly configured but that’s just as likely a user error
  • ChrisArchitect3 hours ago
    the irony of the submitted url having a weird double slash &#x2F;&#x2F; in it.
  • gjvc8 hours ago
    bad example in the article:<p><pre><code> export PATH=&quot;$PATH:$HOME&#x2F;.local&#x2F;bin&#x2F;&quot; </code></pre> better:<p><pre><code> export PATH=&quot;$HOME&#x2F;.local&#x2F;bin&#x2F;:$PATH&quot;</code></pre>
    • Backslasher8 hours ago
      Afaik it&#x27;s habit to give system paths precedence so a malicious script can&#x27;t shadow e.g. sudo and steal your password, escalating a local file write into root
      • toast08 hours ago
        Otoh, if you don&#x27;t put your local path first, you can&#x27;t override system binaries that you want to override.<p>Also, if something can write into your path, it can <i>probably</i> write to your shell config and&#x2F;or the environment variables.
        • stkdump3 hours ago
          Why would you want to override system binaries
          • toast03 hours ago
            Often, system binaries are <i>ancient</i>
            • BenjiWiebe3 hours ago
              Are you a MacOS user by any chance?
      • 3eb7988a16632 hours ago
        All sorts of utilities push themselves to the front of path: uv, mise, asdf, python virtual environments, nix shell, etc.<p>It is a theoretically nice ideal that fails immediately when you want project specific overrides.
        • jdxcode1 hour ago
          That’s not true with mise. You can add something to the front of PATH in front of mise bins and mise will respect that.
      • paulddraper8 hours ago
        AFAIK it&#x27;s habit to allow your scripts to override system ones, so you can customize behavior.<p>I&#x27;ve always seen home dir, homebrew, etc prepending to PATH.
      • marcosdumay6 hours ago
        That&#x27;s important only for the people that add relative names (like &#x27;.&#x27;) to their path.<p>Most people know better.
      • gjvc6 hours ago
        by that time it&#x27;s too late and should have been prevented appearing on the host much earlier
  • NotMichaelBay4 hours ago
    Alternative title: There&#x27;s no place like $HOME
  • IshKebab9 hours ago
    Bash footgun #238503.
    • paulddraper8 hours ago
      That&#x27;s standard POSIX.<p><i>Tilde expands when at the beginning of an unquoted word.</i><p>Pretty straightforward.<p><pre><code> ~ or ~&#x2F; --&gt; $HOME ~user --&gt; user&#x27;s home </code></pre> ---<p>Bash has a few extra.<p><pre><code> ~+ --&gt; $PWD ~- --&gt; $OLDPWD ~+N or ~-N --&gt; dirs</code></pre>
      • Joel_Mckay7 hours ago
        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<p>scriptPath=$(&#x2F;usr&#x2F;bin&#x2F;realpath &quot;${BASH_SOURCE[0]}&quot;)<p>localPath=$(&#x2F;usr&#x2F;bin&#x2F;dirname &quot;$scriptPath&quot; )<p>&#x2F;usr&#x2F;bin&#x2F;echo &quot;localPath = &#x27;$localPath&#x27;&quot;
    • slashdave6 hours ago
      <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;The_UNIX-HATERS_Handbook" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;The_UNIX-HATERS_Handbook</a>
    • _ZeD_8 hours ago
      well.. it&#x27;s in zsh (and probably any other *sh) too
      • vbernat8 hours ago
        In Zsh, you can set PATH with path=(~&#x2F;.local&#x2F;bin $path). There, it works as shell expansion works.
        • kccqzy8 hours ago
          In fish, you can just do `fish_add_path ~&#x2F;.local&#x2F;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.<p><a href="https:&#x2F;&#x2F;fishshell.com&#x2F;docs&#x2F;current&#x2F;cmds&#x2F;fish_add_path.html" rel="nofollow">https:&#x2F;&#x2F;fishshell.com&#x2F;docs&#x2F;current&#x2F;cmds&#x2F;fish_add_path.html</a>
  • sasamsm753 hours ago
    [flagged]
  • aarunsoman4 hours ago
    [flagged]
  • hnd9q09qk48 hours ago
    [flagged]
  • nailer4 hours ago
    [dead]
  • ska12967 hours ago
    [flagged]
  • mr_mitm8 hours ago
    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.
    • jetbalsa8 hours ago
      What about people who do not speak English? or even use Latin letters?
      • mr_mitm8 hours ago
        The language I grew up with does use non latin letters, I can manage. Then again, it&#x27;s only four of them, so I get your point ... but I can dream, can&#x27;t I?
      • ThunderSizzle8 hours ago
        What Latin letter(s) are you referring to?<p>The (classical) Latin alphabet can be fully described by the English alphabet.
        • toast08 hours ago
          What about people who do not ((speak English?) or (even use Latin letters?))
        • cowboylowrez8 hours ago
          unicode names <i>spit</i>
          • jetbalsa5 hours ago
            if I want to name my file &lt;turd emoji&gt;.txt I damn well will
            • mnw21cam2 hours ago
              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&#x27;s fun to see how much software chokes on that!
    • Dylan168077 hours ago
      If you&#x27;re trying to avoid headaches then definitely don&#x27;t allow -. At least not as the first character in a segment.<p>And allowing any letters from any language is probably worth the hassle.
    • dylan6048 hours ago
      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.