Bash brace expansion after a path slash

bashbrace-expansion

I'm trying to copy a file to a different name into the same directory using brace expansion. I'm using bash 4.4.18.

Here's what I did:

cp ~/some/dir/{my-file-to-rename.bin, new-name-of-file.bin}

but I get this error:

cp: cannot stat '/home/xyz/some/dir/{my-file-to-rename.bin,': No such file or directory

Even a simple brace expansion like this gives me the same error:

cp {my-file-to-rename.bin, new-name-of-file.bin}

What am I doing wrong?

Best Answer

The brace expansion syntax accepts commas, but it does not accept a space after the comma. In many programming languages, spaces after commas are commonplace, but not here. In Bash, the presence of an unquoted space prevents brace expansion from being performed.

Remove the space, and it will work:

cp ~/some/dir/{my-file-to-rename.bin,new-name-of-file.bin}

While not at all required, note that you can move the trailing .bin outside the braces:

cp ~/some/dir/{my-file-to-rename,new-name-of-file}.bin

If you want to test the effect of brace expansion, you can use echo or printf '%s ', or printf with whatever format string you prefer, to do that. (Personally I just use echo for this, when I am in Bash, because Bash's echo builtin doesn't expand escape sequences by default, and is thus reasonably well suited to checking what command will actually run.) For example:

ek@Io:~$ echo cp ~/some/dir/{my-file-to-rename,new-name-of-file}.bin
cp /home/ek/some/dir/my-file-to-rename.bin /home/ek/some/dir/new-name-of-file.bin
Related Question