I know there is something different about the environment of the Terminal command-line and the environment in a bash script, but I don't know what that difference is…
Here is the example which finally led me to ask this quesiton; it may flush out some of the differences.
I am trying to strip leading '0's from a number, with this command.
var="000123"; var="${var##+(0)}" ; echo $var
When I run this command from the Terminal's command-line, I get: 123
However, when I run it from within a script, it doesn't work; I get: 000123
I'm using Ubuntu 10.04, and tried all the following with the sam results:
- GNOME Terminal 2.30.2
- Konsole 2.4.5
- #!/bin/bash
- #!/bin/sh
My bash version 4 1 5 1 release i486-pc-linux-gnu (in terminals and scripts)
'shopt' differences between CLI and Script:
CLI Script
on off checkwinsize
on off expand_aliases
on off extglob
on off histappend
off on hostcomplete
What is causing this difference?
Even if some upgrade will make it work in scripts…
I am trying to find out the what and why,
so in future, I'll know what to look out for.
Here are 3 bash ways to strip leading '0's. (I knew only one when I first asked this queston)
var=0001230; var="$[10#$var]"; echo $var # fastest= 1.00 integers only
var=0001230; var="${var##+(0)}"; echo $var # slower x 1.25 works with strings, but requires shopt -s extglob
var=0001230; var="${var#${var%%[!0]*}}"; echo $var # slower x 1.61 works with strings
Best Answer
Your question cannot be answered quite generally. Some comments though. On my version of bash (3.1.17(1)-release), your command doesn't have the desired output even when run from the command line; the same with zsh. So presumably something is fishy about your command. I don't know what "##+(0)" is suppoed to accomplish, but "#0" succeeds in removing one leading zero. This show a way to remove arbitrary numbers of zeros.
If there really is a difference between the behavior on the command line and from a script, then most likely the script uses a different interpreter (different bash version, bash instead of zsh) or different shell options (try running
shopt
). The latter difference might be the result of your interactive shell sourcing$HOME/.bashrc
and$HOME/.profile
whereas scripts generally don't. That shouldn't affect environment variables, as they're inherited if exported, but it should affect shell options, which need to be set in every shell.