简体   繁体   English

这个bash脚本怎么了?

[英]What's wrong with this bash script?

Here's my myscript.sh : 这是我的myscript.sh

alias apt-get-update="apt-get update -qq"
alias apt-get-install="apt-get install -f -y -qq --force-yes"
alias yum-install="yum --quiet --nogpgcheck -y install"

function ensure_cmd_or_install_package_apt(){
    local cmd=$1
    shift
    local pkg=$*

    hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )
}

When I run sh myscript.sh I get: 当我运行sh myscript.sh我得到:

myscript.sh: 5: myscript.sh: Syntax error: "(" unexpected

It looks perfectly fine to me; 对我来说看起来很好 any ideas? 有任何想法吗?

Does running bash myscript.sh fix it? 运行bash myscript.sh是否可以解决问题?

It could be your script is running in dash instead of bash . 可能是您的脚本以dash而不是bash运行。

According to this answer you can change it with the following command: 根据此答案,您可以使用以下命令对其进行更改:

chsh

Also in general you should be explicit in your script header as to the app/shell you want to run the script with: 同样,通常,您应该在脚本头中明确显示要使用以下命令运行脚本的应用程序/ shell:

#!/bin/bash

If the script requires bash-isms then you should tell it to run with bash. 如果脚本要求使用bash-isms,则应告诉它与bash一起运行。

In your case you are on ubuntu (confirm) and ubuntu uses dash as the default shell (ie /bin/sh is a symlink to dash). 在您的情况下,您使用的是ubuntu(确认),并且ubuntu使用破折号作为默认外壳程序(即/ bin / sh是破折号的符号链接)。 Dash doesn't allow: 破折号不允许:

function name () {}

and instead just wants: 而是只想要:

name () {}

In fact the first form should be avoided if possible since it's not portable. 实际上,如果可能的话,应该避免第一种形式,因为它不是便携式的。 But if you use the function keyword, don't use parens since they are not required (it's an accident that it even works). 但是,如果您使用function关键字,请不要使用括号,因为它们不是必需的(这是偶然的,甚至可以使用)。

With regards to setting a script header, sometimes it's better to use env to find the program (say in the case of ruby or perl for instance where you might have numerous ruby/perl executables but the one furthest up on your path is the one you want to run with). 关于设置脚本头,有时最好使用env查找程序(例如在ruby或perl的情况下,例如,您可能有很多ruby / perl可执行文件,但是路径上最远的一个是您想要一起运行)。

#!/usr/bin/env ruby

Is the way to go. 是要走的路。 Usually for shells, /bin/bash or /bin/csh etc is sufficient in your shebang, but never assume :). 通常对于shell,/ bin / bash或/ bin / csh等足以满足您的需求,但是请不要假设:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM