Syntax error in sh - built and working for bash [duplicate]

落花浮王杯 提交于 2019-11-28 10:55:22

问题


I just started learning bash and have a few scripts working together fine from the command line and via udev.

However I just installed AT so I could get around some udev limitations.

It's taken me forever to first notice that AT is very obvious about using sh - not bash, and that was causing my source command to fail. I since replaced it with the more portable ., that should work with all of the shells.

But now I get a sh syntax error when I declare variables using brackets to surround sourced variables that have double quotes in them.

I'd like to fix this syntax error in sh "(" unexpected - and if someone could suggest an alternative that works for both sh and bash, that would be great. Otherwise a sh fix would at least get me going again.

These are the few lines in the working bash script:

#!/bin/bash
#
# inlinetest.sh
#
CONFIG_FILE=/home/pi/autostart/autostart-settings.cfg

# Check if file exists
if [ ! -f "$CONFIG_FILE" ]; then
    exit 1
else
   # process stream settings - source is only in bash
   # use . for sh and bash shell functionality (AT uses sh)
  . "$CONFIG_FILE"
fi

# Function to wrap arecord and avconv into one command
pipe_cmd() {
   sudo nohup sudo /home/pi/aplay/arecord2 -f cd -D plughw:1,0 -q | /usr/bin/avconv "$@" >/dev/null 2>&1 &
} 

stream_parameters=(-ice_name "$icecast_show" -f mp3)   
icecast_setup="icecast://$icecast_user:$icecast_password@$icecast_server:$icecast_port$icecast_mount_url"
stream_args=(-re -i - -c:a libmp3lame -ac 2 -ar 44100 -content_type audio/mpeg -loglevel quiet -b:a "$stream_bitrate" -legacy_icecast "$icecast_legacy") 

pipe_cmd "${stream_args[@]}" "${stream_parameters[@]}" "$icecast_setup"

Syntax error occurs on this line:

stream_parameters=(-ice_name "$icecast_show" -f mp3)

and will probably do same thing on this one:

stream_args=(-re -i - -c:a libmp3lame -ac 2 -ar 44100 -content_type audio/mpeg -loglevel quiet -b:a "$stream_bitrate" -legacy_icecast "$icecast_legacy") 

EDIT

This message is returned by ShellCheck when I change the shell to /bin/sh

In POSIX sh, arrays are undefined

回答1:


sh does not have arrays (or, rather, it has only one), and stream_parameters=(-ice_name "$icecast_show" -f mp3) is a syntax error. If you want to use the one array that you have available, you can do something like

set -- -ice_name "$icecast_show" -f mp3   
icecast_setup="icecast://$icecast_user:$icecast_password@$icecast_server:$icecast_port$icecast_mount_url"
set -- "$@" -re -i - -c:a libmp3lame -ac 2 -ar 44100 -content_type audio/mpeg -loglevel quiet -b:a "$stream_bitrate" -legacy_icecast "$icecast_legacy" 


pipe_cmd "$@"  "$icecast_setup"


来源:https://stackoverflow.com/questions/38365845/syntax-error-in-sh-built-and-working-for-bash

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