How do I get 0-padded numbers in {} (brace expansion)?
Bash brace expansions could generate the numbers with leading zeros (since bash 4.0 alpha+ ~2009-02-20):
$ echo {001..023}
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023
So, you can do:
for a in {001..218}; do echo "bvrprdsve$a; $(ssh -q bvrprdsve$a "echo \$(free -m|grep Mem|/bin/awk '{print \$4}';free -m|grep Swap|/bin/awk '{print \$4}')")"; done >> /tmp/svemem.txt
But, let's look inside the command a little bit:
You are calling free twice, using grep and then awk:
free -m|grep Mem |/bin/awk '{print \$4}'; free -m|grep Swap|/bin/awk '{print \$4}'
All could be reduced to this one call to
free
andawk
:free -m|/bin/awk '/Mem|Swap/{print \$4}'
Furthermore, the internal command could be reduced to this value:
cmd="echo \$(free -m|/bin/awk '/Mem|Swap/{print \$4}')"
Then, the whole script will look like this:
b=bvrprdsve;
f=/tmp/svemem.txt;
cmd="echo \$(free -m|/bin/awk '/Mem|Swap/{print \$4}')";
for a in {001..218}; do echo "$b$a; $(ssh -q "$b$a" "$cmd")"; done >> "$f";
printf '%04d' "$a"
will output a zero-filled four digit string if $a
is an integer.
Example:
a=14
printf -v b '%04d' "$a"
printf '%s\n' "$b"
will output
0014
So just loop as before and create your zero-filled variable and use that:
for a in {1..9}; do
printf -v za '%04d' "$a"
# rest of code, using $za
done
The assignment to za
above could also be done with
printf -v za '%04d' "$a" # print to variable za
To be more readable to the C programmer
for (( a = 1; a < 10; ++a )); do
printf -v za '%04d' "$a"
# rest of code, using $za
done
I haven't looked at the rest of the code.
Note: In ksh
one may set an attribute on a variable so that its expansion is always zero-filled:
typeset -Z4 za
for (( a = 1; a < 10; ++a )); do
za="$a"
printf "%s\n" "$za"
done
0001
0002
0003
0004
0005
0006
0007
0008
0009
You could use seq -w 1 218
or seq -f "%03g" 1 218
to generate your numbers.