Question

Hi I am writing a bash script and have a few int variables. What I am trying to do is make them have length of 6 for when I echo them out. I am not sure how to do this if say the length of the variable is 2 or if I run the script again and the variable has a shorter or longer length.

Was it helpful?

Solution

Use printf to pad a value to a desired length:

printf '%06d\n' "$value"     # pad with 0's
printf '%6d\n'  "$value"     # pad with spaces, right aligned
printf '%-6d\n' "$value"     # pad with spaces, left aligned

If you're working with numbers it would be a bit unusual to strip of excess digits. But if you wanted to, you could display only the first 6:

printf '%06d\n' "${value::6}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top