Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether string starts with "!" in POSIX sh

Tags:

sh

Trying to create a condition based on whether the line starts with an "!".

Note: this is sh not bash

#!/bin/sh

if [ $line = "!*" ] ;
then
    echo "$0: $line has !"
else
    echo "$0: $line has no !"
fi
like image 558
Scott Stamile Avatar asked Feb 21 '18 19:02

Scott Stamile


People also ask

How do you check if a string starts with a substring in shell script?

We can use the double equals ( == ) comparison operator in bash, to check if a string starts with another substring. In the above code, if a $name variable starts with ru then the output is “true” otherwise it returns “false”.

What is Posix sh?

2. POSIX Shell : POSIX Shell is a command line shell for computer operating system which was introduced by IEEE Computer Society. POSIX stands for Portable Operating System Interface. POSIX Shell is based on the standard defined in Portable Operating System Interface (POSIX) – IEEE P1003.

How do you check if a variable contains a string in Linux?

Using Regex Operator Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ .

How check if string is in Unix?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.


2 Answers

In POSIX test, = performs exact string comparisons only.

Use a case statement instead.

case $line in
  "!"*) echo "$line starts with an exclamation mark" ;;
  *)    echo "$line does not start with an exclamation mark" ;;
esac

If you really want to put this in an if, you can do that:

if case $string in "!"*) true;; *) false;; esac; then
  echo "$line starts with an exclamation mark"
else
  echo "$line does not start with an exclamation mark"
fi
like image 96
Charles Duffy Avatar answered Sep 21 '22 15:09

Charles Duffy


You can use the standard POSIX parameter substitution syntax.

${var#repl} will remove the repl from the beginning of the content of the $var variable.

So, you'll have:

$ var=test
$ echo ${var#t}
est
$ echo ${var#X}
test

So, in order to have a simple if statement to check if a variable starts with a string (! in your case), you can have:

#!/bin/sh

if test "$line" = "${line#!}"; then
    echo "$0: $line has no !"
else
    echo "$0: $line has !"
fi

PS: test ... is equivalent to [ ... ], so the above script is exactly the same as

#!/bin/sh

if [ "$line" = "${line#!}" ]; then
    echo "$0: $line has no !"
else
    echo "$0: $line has !"
fi
like image 36
Michele Locati Avatar answered Sep 20 '22 15:09

Michele Locati