Bash check if string starts with character such as #

My bash shell script read a config file line-by-line using a bash while loop. I need to check if a string stored in $var starts with some value such as # character. If so I need to ignore that value and read the next line from my config file. How do I check if variable begins with # in bash shell scripting running on a Linux or Unix-like operating systems?

Introduction – In bash, we can check if a string begins with some value using regex comparison operator =~. One can test that a bash variable starts with a string or character in bash efficiently using any one of the following methods.

How to check if a string begins with some value in bash

Let us define a shell variable called vech as follows:
vech="Bus"
To check if string “Bus” stored in $vech starts with “B”, run:
[[ $vech = B* ]] && echo "Start with B"
The [[ used to execute the conditional command. It checks if $vech starts with “B” followed by any character. Set vech to something else and try it again:
vech="Car"
[[ $vech = B* ]] && echo "Start with B"
[[ $vech = B* ]] && echo "Start with B" || echo "Not matched"

Bash check if string starts with character using if statement

if..else..fi allows to make choice based on the success or failure of a command:

#!/bin/bash
input="xBus"
 
if [[ $input = B* ]]
then
	echo "Start with B"
else
	echo "No match"
fi

Bash check if a variable string begins with # value

The syntax is as follows to read a file line-by-line:

#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r var
do
  echo "$var"
done < "$input"

Let us add check to see if $var starts with “#” in bash:

#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r var
do
  #
  # if value of $var starts with #, ignore it
  #
  [[ $var =~ ^#.* ]] && continue
  echo "$var"
done < "$input"

The continue statement resumes the next iteration of the enclosing while loop, so it skips rest of the commands when commented line found out.

How to use regex comparison operator =~ if string starts with character

The syntax is as follows to see if $var starts with “#”:

if [[ "$var" =~ ^#.*  ]]; then
    echo "yes"
fi

Therefor the following is an updated version:

while IFS='|' read -r t u
do
        # ignore all config line starting with '#'
	[[ $t =~ ^#.* ]] && continue
        echo "Working on $t and $u" 
 
done < "$INPUT_FILE"

How to check if a string begins with some value in bash

The case statement is good alternative to multilevel if-then-else-fi statement. It enable you to match several values against one variable. It is easier to read and write:

#!/bin/bash
# set default to 'Bus' but accept the CLI arg for testing
input="${1:-Bus}" 
echo -n "\$input starts with 'B' : "
case "$input" in
    B*)
            echo "yes";;
     *)
            echo "no";;
esac

Conclusion

You learned how to check if a string begins with some value using various methods. For more info read the bash command man page here.


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum