16

On Centos my script work fine. But on Debian Squeeze when I run script, I got:

cpfailover.sh: 30: Bad substitution

Line of script say:

SCRIPT_PATH="${BASH_SOURCE[0]}";

I have seen in many examples, even here, that is a correct line no. where is the problem.

2
  • 1
    Can you use "$0" instead of ${BASH_SOURCE[0]}? AFAIK they should be the same.
    – khachik
    Mar 21, 2013 at 7:45
  • 1
    @khachik: ${BASH_SOURCE[@]} is introduced in Bash 3.0 for debugging purpose. It does not mean the same as $0. According to Bash manual, elements in ${BASH_SOURCE[@]} are the source filenames corresponding to the elements in ${FUNCNAME[@]}.
    – pynexj
    Mar 21, 2013 at 8:33

2 Answers 2

24

Are you using /bin/sh? On Debian Squeeze, /bin/sh is a symlink to /bin/dash which does not support ${array[0]}.

2
  • Gracias. Update system for use old bash instead dash and work fine.
    – abkrim
    Mar 21, 2013 at 16:01
  • 6
    Since your script depends on bash specific features I'd suggest you use /bin/bash explicitly.
    – pynexj
    Mar 22, 2013 at 1:44
2

Change your code to

SCRIPT_PATH=$0;

instead of

SCRIPT_PATH="${BASH_SOURCE[0]}";
3
  • could you eleborate on why you feel $0 is "better" than ${BASH_SOURCE[0]}? Jun 9, 2016 at 4:54
  • 3
    It's POSIX /bin/sh compatible, where ${BASH_SOURCE[0]} will only work in bash. Generally, if you're not targeting multiple architectures or old operating systems, you should switch your shebang to #!/bin/bash, so you can use all of bash's features. Bear in mind that Mac OSX ships with bash 3.2, so if you're targeting it you can't use bash-4's features. Oct 3, 2016 at 20:50
  • $0 returns the current working directory; ${BASH_SOURCE[0]} returns the directory in which the script is stored. You can't use $0 to replace ${BASH_SOURCE[0]}
    – Banoona
    Jun 25, 2022 at 8:30

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.