"let" inner shell command not working in shell script?

I did

a=1234 let "a=a+1" 

on the command line, and that's fine. But when I do the same in a shell script. It displays the error message "let: not found". Here is the script file.

 #!/bin/sh a=1234; let "a=a+1"; echo "$a"; 

Thanks,

+7
source share
8 answers

The problem is probably that /bin/sh not the same as or does not behave the same as your normal shell. For example, when bash is called as /bin/sh , it provides a subset of its usual functions.

So, you may need to change your shebang line to use a different shell:

 #!/bin/bash 

or

 #!/bin/ksh 

You do not need half-columns at the ends of the lines.

+7
source

Do not use let . Use the POSIX Arithmetic Extension : a=$(($a+1)) . This is guaranteed to work in any POSIX-compatible shell.

+8
source

See at: http://www.hlevkin.com/Shell_progr/hellobash.htm

Correctly:

 a=1234; b=1; a=`expr $a + $b`; 
+3
source

You should use let a=a+1 without quotes

+2
source

This is the '$ a' of '$ a = 1234' that is killing you.

The shell does all the $ substitutions and THEN evaluates the expression. As a result, he saw "= 1234" because there was no value for $ a.

Use -x to see this.

  bash -x your-script 
+1
source

Check the current shell using the following command at a command prompt:

echo $ SHELL

It will provide a shell name, use instead of / bin / sh in the first line of your script.

0
source
  • Check shell name with

    echo $SHELL

  • Change the first line of the script accordingly to

    #!/bin/bash

    or

    #!/bin/ksh

    instead of #!/bin/sh .

0
source
 c=1 d=1 for i in `ls` do if [ -f $i ] then echo "$c -> $i" c=`expr $c + 1` fi done c=`expr $c - 1` echo no. of files $c for i in `ls` do if [ -d $i ] then echo "$d -> $i" d=`expr $d + 1` fi done d=`expr $d - 1` echo no. of direcrories $d 
-2
source

All Articles