57

Often when moving files around, I need to do the opposite later. So in my .bashrc I included this working code:

rmv() {
  mv $2/${1##*/} ${1%/*}
}

Now I wonder why I can't write this as a single liner. This is what I tried:

rmv() {mv $2/${1##*/} ${1%/*}}

If I do so, I get this error:

-bash: .bashrc: line 1: syntax error near unexpected token `{mv'
Cyrus
  • 84,225
  • 14
  • 89
  • 153
Steffen
  • 601
  • 1
  • 5
  • 5

1 Answers1

116

In Bash, { is not automatically recognized as a special/separate token from what's around it. So you need whitespace between { and mv.

Additionally:

  • } needs to be the start of a command; so if it's not on its own line, you need ; to terminate the previous command.
  • It's a best practice to always use double-quotes around any parameter expansion, since otherwise you'll get bizarre behaviors when the parameters include whitespace or special characters.

So:

rmv() { mv "$2/${1##*/}" "${1%/*}" ; }
ruakh
  • 175,680
  • 26
  • 273
  • 307
  • why don't they fix bash so it doesn't always mess up whitespaces? – Jason May 16 '19 at 18:41
  • 3
    @Jason: The weird behavior with whitespace is specified by POSIX. \[[link](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05)] And, unfortunately, there are a *lot* of existing shell scripts that rely on it. – ruakh May 16 '19 at 18:47
  • 1
    Good info with the closing brace that is the start of a command. It works with semicolon, but where did you get this info? `bash closing brace start of command` in google did not push me on the track. – Timo Apr 14 '22 at 06:15
  • 3
    @Timo: The *Bash Reference Manual* is available online: https://www.gnu.org/software/bash/manual/bash.html. The relevant section is §3.2.5.3 "Grouping Commands": https://www.gnu.org/software/bash/manual/bash.html#Command-Grouping. It words it very differently -- my "start of command" wording isn't really the most accurate -- which is part of why your Google search didn't find it. – ruakh Apr 14 '22 at 06:26
  • @Jason why don't they fix whitespaces so they don't always mess up bash? :D – quetzalcoatl Sep 20 '22 at 08:14