0

I have a variable reponame in Shell Script(bash) holding a string

echo $reponame
"testrepo.git"

I want to remove the last 4 character of this string and assign the result to a new variable repo

echo $repo
"testrepo"

How can I do this?

Raj
  • 63
  • 1
  • 8

1 Answers1

1

If I understand correctly, you want to get rid of the .git extension. Then the correct expression would be

repo=${reponame%.*}

or

repo=${reponame%.git}

for that very specific case.

For substrings in general, the expression removing last 4 characters would go like

repo=${reponame:0:-4}

Very nice resource on Bash string operations: https://tldp.org/LDP/abs/html/string-manipulation.html


For shell in general you might use various approaches such as

repo=$(echo -n "$reponame" | sed 's/\.git$//')

or

repo=$(echo -n "$reponame" | rev | cut -f 2- -d '.' | rev)
Newerth
  • 449
  • 2
  • 12