I would like to ask if how can I remove the space in the beginning of the stored data of the variable. I had an auto-generated script that will get MySQL COUNT from the DB.

MYSQL COUNT SCRIPT-> .ini file (variable holder / parameters) -> report-script

This mean that I have script that will count the some data in the database then it will data will stored in a text(.ini) file as variable then a another script will read the file and look for the variable.

Under the db-count-script.sh here some of related codes on my problem.

mysql_count=$(mysql ... -e"USE my_db;SELECT COUNT(*) FROM my_db.sr1 WHERE intime='1';"

echo $mysql_count #This is the output of this echo --> COUNT(*) 15

#from here I'm going to remove the COUNT(*)

#storing the data to the variable
echo "db_cnt=\""$cnt"\"" >> db-count.ini

Inside the db-count.ini I have this data.

db_cnt=" 7"

I want to remove the whitespace on that variable because I have script to call this variable like this and for the future use I really need the data of the variable clean.

source db-count.ini
echo "Count:"$db_cnt
Count: 7 

Any suggestion? Tips?


  • You can have mysql not output COUNT(*) in the first place with -N or --skip-column-names – dave_thompson_085 Jul 22 '16 at 5:14

To trim whitespace from the front of db_cnt variable in bash use:



$ db_cnt=" 7"
$ echo "$db_cnt"
$ db_cnt="${db_cnt#"${db_cnt%%[![:space:]]*}"}"
$ echo "$db_cnt"

You can use the syntax to customise your script in whatever way you want.

  • db_cnt inside the db_cnt? or you mean sir: db_cnt="${cnt#"${cnt%%[![:space:]]*}"}" – Edmhar Jul 22 '16 at 1:18
  • or cnt="${db_cnt#"${db_cnt%%[![:space:]]*}"}" – Edmhar Jul 22 '16 at 1:19
  • I gave you the line to trim whitespace from a variable. You can customise your script as you want. – techraf Jul 22 '16 at 1:20

A simple echo will remove space fromboth front and back

db_cnt=$(echo $db_cnt)

If you want to remove the whitespace just in front but want to preserve spaces at the end of variable, you can do it using sed as

db_cnt=$(echo "$db_cnt" | sed 's/^ *//')

Converting a line to an array and selecting it's array position will trim spaces.

while read input; do
   if [[ $input =~ COUNT\(\*\) ]]; then
       echo $db_cnt
done < input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.