bash: Bad Substitution

自闭症网瘾萝莉.ら 提交于 2019-11-26 06:19:10

问题


#!/bin/bash

jobname=\"job_201312161447_0003\"
jobname_pre=${jobname:0:16}
jobname_post=${jobname:17}

This bash script gives me Bad substitution error on Ubuntu. Any help will be highly appreciated.


回答1:


The default shell (/bin/sh) under Ubuntu points to dash, not bash.

me@pc:~$ readlink -f $(which sh)
/bin/dash

So if you chmod +x your_script_file.sh and then run it with ./your_script_file.sh, or if you run it with bash your_script_file.sh, it should work fine.

Running it with sh your_script_file.sh will not work because the hashbang line will be ignored and the script will be interpreted by dash, which does not support that string substitution syntax.




回答2:


I had the same problem. Make sure your script didnt have

#!/bin/sh 

at the top of your script. Instead, you should add

#!/bin/bash



回答3:


For others that arrive here, this exact message will also appear when using the env variable syntax for commands, for example ${which sh} instead of the correct $(which sh)




回答4:


Your script syntax is valid bash and good.

Possible causes for the failure:

  1. Your bash is not really bash but ksh or some other shell which doesn't understand bash's parameter substitution. Because your script looks fine and works with bash. Do ls -l /bin/bash and check it's really bash and not sym-linked to some other shell.

  2. If you do have bash on your system, then you may be executing your script the wrong way like: ksh script.sh or sh script.sh (and your default shell is not bash). Since you have proper shebang, if you have bash ./script.sh or bash ./script.sh should be fine.




回答5:


Try running the script explicitly using bash command rather than just executing it as executable.




回答6:


Also, make sure you don't have an empty string for the first line of your script.

i.e. make sure #!/bin/bash is the very first line of your script.




回答7:


Both - bash or dash - work, but the syntax needs to be:

FILENAME=/my/complex/path/name.ext
NEWNAME=${FILENAME%ext}new


来源:https://stackoverflow.com/questions/20615217/bash-bad-substitution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!