14

I newbie in bash scripting but i don't uderstand why it's not work

#!/bin/bash
foo=foobarfoobar
echo ${foo//bar/baz}

bad substitution error on line 3

6
  • It works fine on my shell. What's your default shell? Commented Jan 22, 2012 at 11:26
  • If you're trying to do a substitution, replacing bar with baz, then this is correct. It works on my machine, printing foobazfoobaz, with bash 3.2.48. Commented Jan 22, 2012 at 11:27
  • GNU bash, version 4.2.10(1)-release it works in command line but not in the script Commented Jan 22, 2012 at 11:35
  • @Aristarhys Can you please do echo $0 and uname -a on the command line and add it to your question. Also, if you can paste the error message from the shell. Do ./script.sh on the command line and show the output in your question Commented Jan 22, 2012 at 11:37
  • aristarhys@aristarhys-desktop ~/CADET $ sh test sh test test Linux aristarhys-desktop 3.0.0-12-generic #20-Ubuntu SMP Fri Oct 7 14:50:42 UTC 2011 i686 i686 i386 GNU/Linux test: 5: Bad substitution Commented Jan 22, 2012 at 11:41

2 Answers 2

52

That substitution works fine in Bash 4.2.8 (and looks fine according to the documentation).

My best guess would be that you're not actually using Bash - how are you invoking the script? If you're doing sh script.sh you may well be running it with Dash or something similar (and Dash does indeed give a substitution error on line 3). Try explicitly running it with Bash (bash script.sh).

If it turns out you are actually using Dash, there's some useful information on the differences and how to go back to using Bash (if you want to) here: https://wiki.ubuntu.com/DashAsBinSh

Sign up to request clarification or add additional context in comments.

4 Comments

GNU bash, version 4.2.10(1)-release
If on the command line you did sh scriptname then sh is a link to dash in ubuntu. +1 to @Chris
Oof. God bless the Debian maintainers, but this is subtle and confusing. It would be nice if << sh >> calls generating errors somehow included a warning that Dash, not Bash, is in use.
My problem came from an executable bash script called from within a Makefile.
-2
$ foo=foobarfoobar
$ echo ${foo}/bar/baz
foobarfoobar/bar/baz

Just that you have the braces in the wrong place, but then I am no expert at BASH, so perhaps this isn't the effect you're going for..

3 Comments

${foo//bar/baz} must replace all bar to baz, so echo will be foobazfoobaz tldp.org/LDP/abs/html/string-manipulation.html
OP is doing global substitution using //. I don't think he wants to append bar/baz to his variable. He is looking to replace occurrences of bar with baz so that his output looks like foobazfoobaz
yeah in every bash string manipulation article use such code but it does not work for me

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.