In CPP, we could use apostrophes to delimit digits for better readability: 1'000'000
. Same for underscores in Python: 1_000_000
.
How could we do that in Bash, for a=1000000
?
This is not about the printed output.
In CPP, we could use apostrophes to delimit digits for better readability: 1'000'000
. Same for underscores in Python: 1_000_000
.
How could we do that in Bash, for a=1000000
?
This is not about the printed output.
One way:
a='1''000''000'
$ echo $a
1000000
This is a simple concatenation. AFAIK, there's no built-in to do that.
One other way, using parameter expansion:
$ a='1_000_000'
$ a=${a//_/}
$ echo $a
1000000
For a literal, there are options, but not really any great ones.
You say
This is not about the printed output.
but for some folk it will be, so I will reference this other post about that, and move on.
Giles suggested quotes, which work, but aren't lovely. On that note, I'd like to point out that your own example of 1'000'000
will in fact work just fine; it just puts quotes around the three zeroes in the middle, which when evaluated changes nothing, so it looks fine and has no impact, but is likely to confuse someone reading it later... and in the case of 1'000'000'000
or any other odd number of single ticks, it fails because of unclosed quotes.
You can go halfway between - instead of Giles' quotes around each block, just open and close a pair of quotes between each section, embedding nothing: a=1''000''000
. This eliminates the need for leading and training quotes, but is still ugly.
Another trick you might try is a single-character backslash.
$: a=1\000\000
$: echo $((a/1000))
1000
This escapes the literal digit it precedes, but can be more dangerous, depending on your context, as in some situations it is treated differently.
Obviously, quotes throw caveats on all these, as they will include the "delimiter" characters in the data, which really isn't what you want.
$: a=1\000 ; echo $a # fine, the first zero quoted during assignment
1000
$: a="1\000" ; echo $a # nope, includes the slash
1\000
$: a=$"1\000" ; echo $a # nope, slash again
1\000
$: a=$'1\000' ; echo $a # BIG nope - includes a NULL byte
1