14

Trying to write a bash script and in one part of it I need to take whatever parameter was passed to it and replace the hyphens with underscores if they exist.

Tried to do the following

#!/usr/bin/env bash
string=$1
string=${string//-/_}
echo $string;

It's telling me that this line string=${string//-/_} fails due to "Bad substitution" but it looks like it should do it? Am I missing something?

Octoxan
  • 1,949
  • 2
  • 17
  • 34
  • 1
    What version of Bash? There's nothing wrong with what you posted. – Dennis Williamson Dec 07 '18 at 15:12
  • 4
    What's exact error message? It looks more like you ran the script with something like `sh testScript`, and `sh` isn't actually `bash`. – chepner Dec 07 '18 at 15:21
  • 2
    Possible duplicate of [Replacing some characters in a string with another character](https://stackoverflow.com/q/2871181/608639), [How to replacw one character with two characters using tr](https://stackoverflow.com/q/18365482/608639), [Replace a space with a period in Bash](https://stackoverflow.com/q/5928156/608639), etc. – jww Dec 08 '18 at 06:18
  • @jww except if you actually read what I tried and read those posts, you'd see that I tried that and it didn't work for me using hyphens and underscores. Worked for every other character. – Octoxan Dec 10 '18 at 14:09

1 Answers1

24

There is nothing wrong with your script, and it should work in modern versions of Bash.

But just in case you can simplify that to :

#!/bin/bash

echo "$1" | tr '-' '_'

This is in case that parameter substitution does not work ( which seems to be your case ).

Regards!

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49