Rorro
Rorro

Reputation: 1277

Concatenate strings inside bash script (different behaviour from shell)

I'm trying some staff that is working perfectly when I write it in the regular shell, but when I include it in a bash script file, it doesn't. First example:

m=`date +%m`
m_1=$((m-1))
echo $m_1

This gives me the value of the last month (actual minus one), but doesn't work if its executed from a script.

Second example:

m=6
m=$m"t"
echo m

This returns "6t" in the shell (concatenates $m with "t"), but just gives me "t" when executing from a script.

I assume all these may be answered easily by an experienced Linux user, but I'm just learning as I go.

Thanks in advance.

Upvotes: 0

Views: 6479

Answers (3)

Matt
Matt

Reputation: 2896

First of all, it works fine for me in a script, and on the terminal. Second of all, your last line, echo m will just output "m". I think you meant "$m"..

Upvotes: 0

hmontoliu
hmontoliu

Reputation: 4019

Re-check your syntax.

Your first code snippet works either from command line, from bash and from sh since your syntax is valid sh. In my opinion you probably have typos in your script file:

~$ m=`date +%m`; m_1=$((m-1)); echo $m_1
4
~$ cat > foo.sh
m=`date +%m`; m_1=$((m-1)); echo $m_1
^C
~$ bash foo.sh
4
~$ sh foo.sh
4

The same can apply to the other snippet with corrections:

~$ m=6; m=$m"t"; echo $m
6t
~$ cat > foo.sh
m=6; m=$m"t"; echo $m
^C
~$ bash foo.sh
6t
~$ sh foo.sh
6t

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 601559

Make sure the first line of your script is

#!/bin/bash

rather than

#!/bin/sh

Bash will only enable its extended features if explicitly run as bash. If run as sh, it will operate in POSIX compatibility mode.

Upvotes: 1

Related Questions