开发者

"let" internal shell command doesn't work in a shell script?

I did

a=1234 
let "a=a+1"

on command line and it's fine. But when I do the same in a shell script. It prints out an error that "let: not fou开发者_如何学运维nd". Here is the script file.

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

Thanks,


Do not use let. Use POSIX arithmetic expansion: a=$(($a+1)). This is guaranteed to work in any POSIX-compliant shell.


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

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

#!/bin/bash

or

#!/bin/ksh

You don't need the semi-colons at the ends of the lines.


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

The correct is:

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


You should use let a=a+1 without quotes


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

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

Use -x to see this.

  bash -x your-script


Check your actual shell with the following command in the command line:

echo $SHELL

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


  1. Check the shell name using

    echo $SHELL

  2. Change the first line of the script accordingly to

    #!/bin/bash

    or

    #!/bin/ksh

    instead of #!/bin/sh.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜