1

I have a bash shell script change_filename.sh containing the line of code:

mv "dir\ 1/file1.txt" "dir\ 1/file2.txt"

which does not change the name of file1.txt to file2.txt as expected but produces the error message:

mv: rename dir\ 1/file1.txt to dir\ 1/file2.txt: No such file or directory

It works when I type the same line in Terminal but not in the script. Why does the script not work?

3
  • 5
    To protect the space, either use double quotes or a backslash, but not both Commented Nov 25, 2024 at 15:12
  • @glennjackman Thanks, that works now. Commented Nov 25, 2024 at 15:19
  • Are you sure you typed mv "dir\ 1/file1.txt" "dir\ 1/file2.txt" in a "Terminal" and it succeeded at renaming a file called file1.txt in a directory called dir 1 (and not dir\ 1)? Can you reproduce it? What application was running at the time inside your "Terminal"? Was it a shell? Which one? I don't know of any shell where that would work. Certainly not bash nor zsh (the default login shell on macos these days I believe) Commented Nov 26, 2024 at 6:59

1 Answer 1

1

first possibility

credit @glenn jackman

The escape sequence \ is not defined within quotes by Bash, so it expands to \ (the backslash is preserved). To see this:

  • echo "foo\ bar" -> foo\ bar
  • echo foo\ bar -> foo bar

It's possible, then, that some peculiar quirk with the MacOS terminal leads to the difference in behaviour.

second possibility

When using the script, you need to keep in mind the current working directory. Paths in Bash scripts are resolved relative to the CWD of the shell (process) that invoked the script.

For example, say we have the following file hierarchy, and script.sh contains cat bar/qux.txt.

foo
├── bar
│   └── qux.txt
└── script.sh

Then

  • Invoking script.sh from the foo directory will work (the contents of qux.txt will be printed)
  • Invoking script.sh from anywhere else will not work

To fix this, you can either use a clever Bash expression to figure out the path to the script, and look for bar/qux.txt relative to that, or you can specify the path to qux.txt using a rooted path (e.g. /home/me/...)

2
  • Related: POSIX Shell Command Language - Double-Quotes (scroll down to the "backslash" segment). So, it is not a "possibility", rather it is the standard behavior of the shell that \ doesn't expand to space within double quotes. Commented Nov 25, 2024 at 15:31
  • @Vilinkameni yes, absolutely! I meant 'possibility' in the sense that 'this is possibly what is causing OP's problem' Commented Nov 25, 2024 at 15:54

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.