Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • 97
    None of the current solutions work if there are any newlines at the end of the directory name - They will be stripped by the command substitution. To work around this you can append a non-newline character inside the command substitution - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd && echo x)" - and remove it without a command substitution - DIR="${DIR%x}". Commented Sep 24, 2012 at 12:15
  • 101
    @jpmc26 There are two very common situations: Accidents and sabotage. A script shouldn't fail in unpredictable ways just because someone, somewhere, did a mkdir $'\n'. Commented Mar 28, 2013 at 8:14
  • 40
    anyone who lets people sabotage their system in that way shouldn't leave it up to bash to detect such problems... much less hire people capable of making that kind of mistake. I have never had, in the 25 years of using bash, seen this kind of thing happen anywhere.... this is why we have things like perl and practices such as taint checking (i will probably be flamed for saying that :) Commented Feb 5, 2015 at 0:12
  • 89
    I stronly suggest to read this Bash FAQ about the subject. Commented Jan 30, 2016 at 2:22
  • 3
    @osirisgothra Anyone who thinks the solution to hazardous characters in filenames is not to write robust scripts, but is instead to prevent people (who may at some point create a hazardous name) from ever accessing the system, is going to have a difficult time. Commented May 3, 2024 at 4:15