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

99封情书 提交于 2021-02-08 12:56:34

问题


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 found". Here is the script file.

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

Thanks,


回答1:


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.




回答2:


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




回答3:


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

The correct is:

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



回答4:


You should use let a=a+1 without quotes




回答5:


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



回答6:


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.




回答7:


  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.




回答8:


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


来源:https://stackoverflow.com/questions/6409778/let-internal-shell-command-doesnt-work-in-a-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!