0

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.

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, sorry, I tried with "cat" and it's working perfectly, as you say. Maybe there was some problem with my editor (Crimson). Thanks a lot.
@Rorro; good to know. You may consider mark the answer as valid. Thanks.
1

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.

3 Comments

Yes, first line is "#!/bin/bash", I forgot to say, and it's not working either...
check my answer. It's not an issue with bash/sh since its all valid sh syntax. The OP needs to review any typo he may have done in his scripts. The code he posts is valid (except a typo in his second snippet of code)
@hmontoliu: I figured this to be a typo in the post -- the OP claims the output of the second snippet to be t, not m.
0

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"..

1 Comment

Yes, I ment $m, my mistake :D . Anyway, hmontoliu's answer was enough. I tried creating the script from the shell and it worked. As I said, it could any mistake using a different editor.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.