0

I am trying to replace all white spaces with _. I used the following code:

FONT="DejaVu Sans Mono"
FONT_CODE=${FONT//[ ]/_}
echo $FONT_CODE 

I'm expecting DejaVu_Sans_Mono as the output But I got the following error :

x.sh: 2: Bad substitution

I am not sure what I need to do to get work.

AKMalkadi
  • 291
  • 3
  • 8
  • 2
    You tagged this `shell` - which shell are you using, specifically? POSIX `sh` doesn't support that syntax for example – steeldriver Jun 03 '21 at 00:36
  • @steeldriver I am using Linux mint.. I used the command sh x.sh – AKMalkadi Jun 03 '21 at 00:48
  • Thanks for the hint. I used zsh and it worked for me – AKMalkadi Jun 03 '21 at 00:53
  • 2
    A better soultion would be to add an appropriate "shebang", make the script executable, and then just call it by name, `./x.sh`. See for example [What is the function of bash shebang?](https://unix.stackexchange.com/questions/354509/what-is-the-function-of-bash-shebang) – steeldriver Jun 03 '21 at 00:58

1 Answers1

0

Here is how I solved my issue after getting hints from the comments. I used zsh instead of sh and it worked for me.

First, I had to install zsh:

sudo apt install zsh

Then, I used zsh instead of sh in the terminal:

zsh x.sh

I got no error and this is the output:

DejaVu_Sans_Mono

AKMalkadi
  • 291
  • 3
  • 8
  • To make it work in `sh`, just do `printf '%s' "$FONT" | tr ' ' '_'`. – Kusalananda Jun 03 '21 at 17:11
  • @Kusalananda Well, that's in case if you want to print immediately. What about if you want to assign it to a variable? – AKMalkadi Jun 03 '21 at 20:27
  • Use an ordinary command substitution: `variable=$( printf '%s' "$FONT" | tr ' ' '_' )` I'm also noting that the code in your question ends with outputting the modified value, so it shouldn't be necessary to store it in an intermediate variable. – Kusalananda Jun 03 '21 at 20:27