1

For workflow purposes I would like to write a bash script where I copy a file renaming it with the current date and current git branch name in its target, like this:

$ cp test.txt test-$(date +'%Y-%h-%d')-$(__git_ps1).txt

Say I'm in a branch named feature, the output file name would be (date of today):

test-2017-Nov-5-feature.txt

For the date part (2017-Nov-5), it works fine, but I'm having difficulties to output it along with the current git branch name via $(__git_ps)

What am I doing wrong? Thank you!

Marcelo Cordeiro
  • 172
  • 1
  • 10
  • 1
    it's not rare that branch names come with a `/`. how are you going to handle that? – Jason Hu Nov 05 '17 at 19:38
  • 1
    What is the difficulty you mentioned? – janos Nov 05 '17 at 19:42
  • @HuStmpHrrr 's comment is absolutely right and I should rethink that. @janos, bash shows me the correct usage of `cp` in the output, as though the `__git_ps1` generates a space in the `target_file` – Marcelo Cordeiro Nov 05 '17 at 19:48
  • See https://stackoverflow.com/questions/1417957/show-just-the-current-branch-in-git or https://stackoverflow.com/questions/6245570/how-to-get-the-current-branch-name-in-git – Robert Nov 05 '17 at 19:55

1 Answers1

1

ANSWER:

the problem with your command is the leading space produced by __git_ps1.

You can delete all spaces for example with the following command:

cp test.txt test-$(date +'%Y-%h-%d')-$(__git_ps1 | tr -d '[:space:]').txt

In this way however the output still contains the '(' and ')' that I thought you didn't want (see alternative solution)

NOTE

the possible 'slash in branch name' problem (highlighted by @HuStmpHrrr) can be solved in a similar way, by deleting (like done with spaces) or traslating to compatible character ( | tr '/' '_')

output

normal

test-2017-Nov-06-(master).txt

if the detached working space

test-2017-Nov-06-((2af977d...)).txt

ALTERNATIVE COMMAND:

try using

cp test.txt test-$(date +'%Y-%h-%d')-$(git rev-parse --abbrev-ref HEAD).txt

output

normal

test-2017-Nov-06-master.txt

if the detached working space

test-2017-Nov-06-HEAD.txt

Community
  • 1
  • 1
Carlo Bellettini
  • 1,070
  • 11
  • 19
  • thank you! just a note on the first answer: I had to delete one pipe (before `tr`) and the current branch was outputted like I wanted, thank you again – Marcelo Cordeiro Nov 06 '17 at 21:46