In a Debian Linux shell, I am trying to add the results of two separate commands so that I know the sum of both.
I already tried:
echo $(expr $(du -sh /srv/mysql) + $(du -sh /srv/www))
and variations of it.
It's returning: expr:
"syntax error: unexpected argument ‘/srv/mysql’
"
of course I also tried to paraphrase the folders, etc.
2 Answers 2
Like this:
could be used with any shell (bash, zsh, sh, dash...)
echo "$((
(
$(du -s /srv/mysql | awk '{print 1ドル}') +
$(du -s /srv/www | awk '{print 1ドル}')
) / 1024
))MiB"
Or simply:
du -shc /srv/www /srv/mysql | awk 'END{print 1ドル}'
The -c
act as the count
operator
-
1Good choice about
du -s
instead ofdu -sh
. To avoid cofusion: About theMB
at the end ofecho
, it should not beM
orMiB
?. Because if I'm not wrong Linux works with*bibytes
. For example: ifdu -sh
shows323M
it actually means323MiB
or323 Mibibytes
.Edgar Magallon– Edgar Magallon2022年10月15日 22:43:49 +00:00Commented Oct 15, 2022 at 22:43 -
1Thanks, edited accordinglyGilles Quénot– Gilles Quénot2022年10月15日 23:08:16 +00:00Commented Oct 15, 2022 at 23:08
Assuming you are dealing with integers ...
I note that expr
is considered archaic and obsolete.
It has two main uses, arithmetic and regex matching, both of which are available in most shells.
(By the by, "Debian Linux shell" isn't just one thing; it could be Bash or Dash or indeed whichever shell is chosen when the user is added or changed subsequent.)
For arithmetic, POSIX requires the shell (any shell claiming compliance, including /bin/sh
) to evaluate $(( expression )) according to rules similar to those for integer expressions in the C language, so that $((1+2*3))
should give 7.
The main problem with the original question was that other information besides the digits were included in the output. The first thing to try should be to ask the program generating those digits not to output anything else. Only if that fails, then filter the output. There are many many ways to do that, but the simplest is just
tr -dc 0-9
which will remove everything that's not a digit.
If you need decimal fractions ...
(decimal fractions are usually fixed point, like 1.23, but floating point systems can understand fixed point numbers as well, so you can use either.)
Neither expr
nor $((...))
can cope with decimal fractions. For that you need bc
or to use a separate scripting language that has fixed point or floating point built in, such as awk
or perl
or python
.
echo $(stuff)
?syntax error: unexpected argument ‘/srv/mysql’
that happens becausedu -sh /srv/mysql
returns something like:500M /srv/mysql
and therefore that's not a correct number.du -csh /srv/www /srv/mysql
to get thec
umulative disk usage of both directories (which is not the same as the sum of the disk usage of each run in isolation if both directories contain instances of the same file for instance).