[ad_1]
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.
[ad_2]