0

In a bash script I need to compare the first char of two Strings.

To do this, I use the head operator like this:

var1="foo"
var2="doo"
headVar1=$(head -c1 $var1)
headVar2=$(head -c1 $var2)

if [ $headVar1 == $headVar2 ]
  then
    #miau
fi

But the console says "head: cant open foo for reading: Doesnt exist the file or directorie" And the same with doo

Some help?

Thanks.

2
  • You have so many syntax errors. To get the first char use ${var1:0:1} Commented Nov 8, 2015 at 16:29
  • In addition to all that's said in the answers, == isn't supported in POSIX [. Bash will support it as an extension, but better to use the compliant string comparison operator =. Commented Nov 8, 2015 at 16:42

3 Answers 3

3

head interpreted foo as a filename. See man head on what options are available for the command.

To store command output in a variable, use command substitution:

headVar1=$(printf %s "$var1" | head -c1)

which could be shortened using a "here string":

headVar1=$(head -c1 <<< "$var1")

But parameter expansion is much faster in this case, as it doesn't spawn a subshell:

headVar1=${var1:0:1}
Sign up to request clarification or add additional context in comments.

3 Comments

The first form isn't quite right in all cases. printf '%s\n' "$var1" will more reliably emit the content faithfully and correctly than echo "$var1" will.
@CharlesDuffy: Can you give an example?
Sure: var1=-n (in many versions; the POSIX spec makes this behavior implementation-defined). And if you're following the POSIX spec for echo, then any string with a literal backslash likewise results in implementation-defined output.
1

Your code must be,

var1="foo"
var2="doo"
headVar1=$(head -c1 <<<"$var1")
headVar2=$(head -c1 <<<"$var2")
if [[ "$headVar1" == "$headVar2" ]]
  then
    echo "It's same"
else
    echo "Not same"
fi
  • remove the space which exists next to equal sign (variable assignment part).

  • Use <<< to fed input from a variable to the corresponding function.

  • Variable names must be preceded by the dollar $ symbol.

Comments

0

A circuitous, but POSIX-compatible, solution:

var1="foo"
var2="doo"
headVar1=${var1%${var1#?}}
headVar2=${var2%${var2#?}}

if [ "$headVar1" = "$headVar2" ]
then
    #miau
fi

${var1#?} expands to the value of var1 minus its first character. That is used as the suffix to remove with ${var1%...}, leaving in the end just the first character of var1.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.