为什么我的 shell 脚本会给出错误:“声明:未找到”?

Tim*_*Tim 6 bash shell-builtin

这是一个简单的示例,显示declare在脚本中使用脚本将不会运行,而获取脚本将:

$ cat /tmp/new
#! /bin/sh
declare -i  hello
$ chmod a+rwx /tmp/new
$ /tmp/new
/tmp/new: 3: declare: not found
$ source /tmp/new
$ 
Run Code Online (Sandbox Code Playgroud)

我想知道为什么直接运行脚本不起作用,而采购它呢?我怎样才能使第一个工作?谢谢!

Sté*_*nez 11

declare是一个内置函数,它不能用于/bin/sh,只能用于bashzsh(可能还有其他外壳)。语法可能因一种外壳而异。您必须相应地选择您的 sheebang ( #!):如果脚本需要由 bash 运行,则第一行必须是

#!/bin/bash
Run Code Online (Sandbox Code Playgroud)

或者

#!/usr/bin/env bash
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 8

declare是 bash 和 zsh 扩展。在您的系统上,/bin/sh既不是 bash 也不是 zsh(可能是 ash),因此declare不可用。您可以使用typeset代替declare;它们是同义词,但typeset也适用于 ksh。在 ash 中,没有typeset -itypeset内置函数等效或大多数其他用途。你实际上并不需要typeset -i声明一个整型变量;它所做的只是允许一些语法快捷方式,例如hello=2+2for hello=$((2+2))